【问题标题】:Convert Base64 string to an image file? [duplicate]将 Base64 字符串转换为图像文件? [复制]
【发布时间】:2013-02-15 17:17:45
【问题描述】:

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

【问题讨论】:

    标签: php base64


    【解决方案1】:

    您需要删除图像数据开头的data:image/png;base64, 部分。实际的base64 数据紧随其后。

    只需剥离包括base64, 在内的所有内容(在对数据调用base64_decode() 之前)就可以了。

    【讨论】:

    • 尝试了不同的解决方案,但这一个在任何地方都有效。
    【解决方案2】:

    这段代码对我有用。

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

    【讨论】:

      【解决方案3】:

      我正在使用的一种简单方法:

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

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

      【讨论】:

      • 巧妙 - 感谢您的回答。请记住,您实际上需要 data:image/png;base64,在开始时,否则 file_get_contents() 将失败。
      • 这个解决方案比公认的答案更好。
      • 是的,更好、更简单的解决方案。您可以使用标识符字符串data:image/png;base64 制作文件扩展名(如果需要)。
      【解决方案4】:

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

          $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',
          ],
      

      【讨论】:

      • laravel's filesystem.php AND Storage::disk('public_feeds')-&gt;put() 帮助我解决了我的问题,帮助我在我们想要的文件夹中取出文件
      【解决方案5】:
      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";
      }
      }
      

      【讨论】:

      • 欢迎来到 Stack Overflow!感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。一个正确的解释would greatly improve 它的长期价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
      • 这不是答案,甚至与原始问题无关。
      【解决方案6】:
      $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

      【讨论】:

        【解决方案7】:

        可能是这样的

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

        【讨论】:

        • 这很有魅力!万分感谢!正是我想要的。只是稍作改动以符合我的具体要求,并让一切正常工作。
        【解决方案8】:

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

        【讨论】:

        • 我有非常聪明的解决方案 $filename_path = md5(time().uniqid()).".jpg"; $decoded=base64_decode($base64_string_img); file_put_contents("uploads/".$filename_path,$decoded);
        • 我只有原始的 base64 数据,没有任何前缀左右。因此我不得不将 $data[1] 更改为 $data[0]。
        • @rcpfuchs 如果你只有原始的base64,那么有什么需要使用$data,直接使用它在问的问题中写的
        • 兄弟你救了我的命!
        • @DanieleTesta 你必须提供一些基准来量化 waaaay 更有效:)
        猜你喜欢
        • 2013-04-19
        • 2014-09-14
        • 2018-09-07
        • 2014-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多