我有包含图像的对象作为基础64字符串,该对象还包含图像的文件名和文件类型(jpeg, png, gif &Bmp)的图像。base 64字符串已经有了标签(例如:"data:image/png;base64"从开头删除。
$myImg对象的格式如下:
-
$myImg->fileName包含转换后的图像应该保存在的名称。
-
$myImg->fileType描述文件应该保存的格式-这用于在fopen()函数中指定路径扩展名。
-
$myImg->b64包含代表图像的64位二进制字符串。
我的函数代码如下:
function toImg(ImageString $myImg){
//Output file is in the same directory as the PHP script.
//Uses the object's filetype attribute as the file extension.
$outputFile = fopen($myImg->fileName . "." . $myImg->fileType, "w");
$image = base64_decode($myImg->b64);
fwrite($outputFile, $image);
fclose($outputFile);
}
该函数创建了图像文件,但我在Xubuntu图像查看器中查看它们时会出现错误。错误如下:
解释JPEG图像文件错误(不是JPEG文件:以0x14 0x00开头)
读取PNG图像文件时出现致命错误:不是PNG文件
文件不显示为GIF文件
我已经看过并遵循base64到图像转换的指南,但他们都没有遇到这些错误。
尝试在浏览器中内联显示图像,如下所示:
<img src="data:image/png;base64,the-base64-string" />
(将png
更改为正确的图像格式)
如果图像仍然破碎,则图像数据无效
您可以像这样从base64解码图像:
function base64_to_jpeg_img($base64_img_string, $output_img) {
$input_file_open = fopen($output_img, "wb");
$data = explode(',', $base64_img_string);
fwrite($input_file_open, base64_decode($data[1]));
fclose($input_file_open);
return $output_img;
}
希望这对你有帮助!