【问题标题】:Base64 image string into image file using PHP使用 PHP 将 Base64 图像字符串转换为图像文件
【发布时间】:2020-04-19 06:36:35
【问题描述】:

我需要代码将 base64 图像字符串转换为图像文件并使用 PHP 写入本地目录。我试过了:

function user_profile_photo(){
            $input = urldecode(file_get_contents('php://input'));
            $received = json_decode($input, true);
            $user_id = $received['user_id'];
            $img = $received['imagecode'];
            $imagedata = base64_decode($img);
            $image_path='uploads/images/'.$user_id;             
            $path = '/var/www/html/empengapp/uploads/images/'.$user_id;
            if (!file_exists($path)) {
                   mkdir($path, 0755, true);
             }

$new_name = date('ymd').time().'.jpg';
$pathwithfile = '/var/www/html/empengapp/uploads/images/'.$user_id.'/'.$new_name;
$success = file_put_contents($pathwithfile, $imagedata);
var_dump($imagedata);exit;




            $this->output
                ->set_status_header(200)
                ->set_content_type('application/json', 'utf-8')
                ->set_output(json_encode($resp, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
                ->_display();
                exit;
    }//end of function user_profile_photo

它正在写入具有给定扩展名的文件,但是当您尝试打开文件时,它会显示无效文件错误。

【问题讨论】:

  • 它是来自原始的有效编码 base64 吗? ($img)
  • 请显示 $img(但请分享一个小图像的示例!)。 edit你的问题添加一个例子。
  • 是的,它是我在服务器上接收的有效 base64 编码字符串。并将其解码为第一行。
  • 我的图片 base64 字符串太长。您可以使用codebeautify.org/image-to-base64-converter在线将任何文件转换为base64字符串。
  • 我知道如何将任何文件转换为 base64,但要找出问题所在,我想查看您的文件。你可以上传你的文件到base64decode.org(在Decode files from Base64 format下)看看你的base64图片是否正确。

标签: php file-upload base64 web-development-server


【解决方案1】:

我想出了解决办法。

        $pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'

         $ifp = fopen( $pathwithfile, 'wb' ); 

			    // split the string on commas
			    // $data[ 0 ] == "data:image/png;base64"
			    // $data[ 1 ] == <actual base64 string>
			    $data = explode( ',', $imagedata );
			    $success = fwrite( $ifp, base64_decode( $data[ 1 ] ) );			    // clean up the file resource
			    fclose( $ifp );
          
          

我通过 API 发送到 PHP 服务器。您需要对图像 base64 字符串进行编码,并且图像 base64 字符串必须包含“data:image/jpeg;base64”。我们在 PHP 服务器上拆分它但是不要想在没有“data:image/jpeg;base64”的情况下发送图像 base54。
但记住一件事你必须使用图片 base64,包括

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-07
    • 2014-07-21
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2012-03-14
    相关资源
    最近更新 更多