【发布时间】: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