php 将 Base64 字符串转换为图像文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15153776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Base64 string to an image file?
提问by Badal
I am trying to convert my base64 image string to an image file. This is my Base64 string:
我正在尝试将我的 base64 图像字符串转换为图像文件。这是我的 Base64 字符串:
Using following code to convert it into an image file:
使用以下代码将其转换为图像文件:
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' );
But I am getting an error of invalid image, whats wrong here?
但是我收到了一个错误invalid image,这里有什么问题?
回答by Austin Brunkhorst
The problem is that data:image/png;base64,is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.
问题是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;
}
回答by aaaaaa123456789
You need to remove the part that says data:image/png;base64,at the beginning of the image data. The actual base64 data comes after that.
您需要删除data:image/png;base64,图像数据开头的部分。实际的 base64 数据在此之后。
Just strip everything up to and including base64,(before calling base64_decode()on the data) and you'll be fine.
只需将所有内容都剥离并包括base64,(在调用base64_decode()数据之前),你会没事的。
回答by Tri?nh Tro?ng Tra?n Ba?
An easy way I'm using:
我正在使用的一种简单方法:
file_put_contents($output_file, file_get_contents($base64_string));
This works well because file_get_contentscan read data from a URI, including a data:// URI.
这很有效,因为file_get_contents可以从 URI 读取数据,包括 data:// URI。
回答by Shimon Doodkin
maybe like this
也许像这样
function save_base64_image($base64_image_string, $output_file_without_extension, $path_with_end_slash="" ) {
//usage: if( substr( $img_src, 0, 5 ) === "data:" ) { $filename=save_base64_image($base64_image_string, $output_file_without_extentnion, getcwd() . "/application/assets/pins/$user_id/"); }
//
//data is like: data:image/png;base64,asdfasdfasdf
$splited = explode(',', substr( $base64_image_string , 5 ) , 2);
$mime=$splited[0];
$data=$splited[1];
$mime_split_without_base64=explode(';', $mime,2);
$mime_split=explode('/', $mime_split_without_base64[0],2);
if(count($mime_split)==2)
{
$extension=$mime_split[1];
if($extension=='jpeg')$extension='jpg';
//if($extension=='javascript')$extension='js';
//if($extension=='text')$extension='txt';
$output_file_with_extension=$output_file_without_extension.'.'.$extension;
}
file_put_contents( $path_with_end_slash . $output_file_with_extension, base64_decode($data) );
return $output_file_with_extension;
}
回答by shubham sachan
That's an old thread, but in case you want to upload the image having same extension-
这是一个旧线程,但如果您想上传具有相同扩展名的图像-
$image = $request->image;
$imageInfo = explode(";base64,", $image);
$imgExt = str_replace('data:image/', '', $imageInfo[0]);
$image = str_replace(' ', '+', $imageInfo[1]);
$imageName = "post-".time().".".$imgExt;
Storage::disk('public_feeds')->put($imageName, base64_decode($image));
You can create 'public_feeds' in laravel's filesystem.php-
您可以在 laravel 的 filesystem.php- 中创建“public_feeds”
'public_feeds' => [
'driver' => 'local',
'root' => public_path() . '/uploads/feeds',
],
回答by Sathish Visar
if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";
$status = file_put_contents($path,base64_decode($image));
if($status){
echo "Successfully Uploaded";
}else{
echo "Upload failed";
}
}
回答by Fazil Raza
This code worked for me.
这段代码对我有用。
<?php
$decoded = base64_decode($base64);
$file = 'invoice.pdf';
file_put_contents($file, $decoded);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
回答by Manish
$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";
This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma
这对于图像处理来说就足够了。特别感谢Dev Karan Sharma 先生

