我正在try 将Base64图像字符串转换为图像文件.这是我的base64字符串:

http://pastebin.com/ENkTrGNG

使用以下代码将其转换为图像文件:

function base64_to_jpeg( $base64_string, $output_file ) {
    $ifp = fopen( $output_file, "wb" ); 
    fwrite( $ifp, base64_decode( $base64_string) ); 
    fclose( $ifp ); 
    return( $output_file ); 
}

$image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' );

但是我得到了一个invalid image的误差,这里怎么了?

推荐答案

问题是编码内容中包含了data:image/png;base64,.当base64函数对图像数据进行解码时,这将导致图像数据无效.在解码字符串之前,删除函数中的数据,如下所示.

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

Php相关问答推荐

Laravel有一个具有两个匹配字段

在php中有没有办法比较两个包含相同枚举类型的枚举数组

向在添加到购物车上动态创建的WooCommerce产品添加发货类别

自定义WooCommerce帐户下载列表

与会者在WooCommerce中按购物车项目数量自定义 checkout 字段

PHP日期操作,将多个日期输出为格式化字符串

WooCommerce数量减号和加号图标未显示

Laveel Livewire Get Groupby姓名列表

如何将WooCommerce产品属性术语名称显示为链接术语?

不包括WooCommerce中单独销售的产品

如何实现对数据库表中多列的唯一约束?

添加并显示单价字段到WooCommerce产品变化

使用PHP编码的字符串与使用OpenSSL编写的shell 代码之间的差异

如何在laravel中使用script type= text/html/script

服务器迁移后无法上载文件-可能存在权限问题

WooCommerce中基于用户角色的不同产品差价

为WooCommerce中存储一些数据的购物车项目添加复选框

随机显示WordPress快捷代码功能时出现问题

在 php 中生成 MAC ISO/IEC 9797-1

Laravel 从嵌套数组的第二级获取最后一项