将Base64字符串转换为图像文件?

时间:2013-03-01 08:49:52

标签: php base64

我正在尝试将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的错误,这里有什么问题?

8 个答案:

答案 0 :(得分:229)

问题在于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; 
}

答案 1 :(得分:41)

您需要删除在图像数据开头显示data:image/png;base64,的部分。之后是实际的base64数据。

只需删除所有内容,包括base64,(在调用数据base64_decode()之前),您就可以了。

答案 2 :(得分:12)

也许就像这样

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;
}

答案 3 :(得分:8)

我正在使用的简单方法:

file_put_contents($output_file, file_get_contents($base64_string));

这很有效,因为file_get_contents可以从URI读取数据,包括data:// URI。

答案 4 :(得分:0)

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";
}
}

答案 5 :(得分:0)

这是一个旧线程,但是如果您要上传具有相同扩展名的图像-

    $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));

您可以在laravel的filesystem.php-

中创建“ public_feeds”
   'public_feeds' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads/feeds',
    ],

答案 6 :(得分:0)

这段代码对我有用。

<?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;
}
?>

答案 7 :(得分:-4)

$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]";
  

这足以进行图像处理。特别感谢Mr. Dev Karan Sharma

相关问题