[英]Base64 image string into image file using PHP
我需要将 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
它正在写入具有给定扩展名的文件,但是当您尝试打开文件时,它会显示无效文件错误。
我想出了解决办法。
$pathwithfile = 'your file path with image name';//eg '/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 包括
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.