繁体   English   中英

base64 图像到 imagecreatefromstring() 丢失数据

[英]base64 image to imagecreatefromstring() losing data

我正在使用axios通过 ajax 发送 base64 字符串。 使用下面的方法,当它从 base64 数据编码回 jpg 时,我以某种方式丢失了大量数据。 我怎样才能在不丢失数据的情况下发送这个?

我从输入中获取文件并将其发送到

var reader = new FileReader();
reader.readAsDataURL(file);

并且该 base64 字符串作为带有 axios 的 ajax 发送为

axios.post('url', {main: img})

一个 php 脚本接收帖子为:

$incoming = json_decode(file_get_contents('php://input'))->main;
$mainImage = str_replace('data:image/jpeg;base64,', '', $incoming);
$img = imagecreatefromstring(base64_decode($mainImage));
$imageSave = imagejpeg($img, './uploaded.jpg');

比如最近在服务器上保存的一个文件只有14k,但是我上传到输入栏的原始文件是19k。 我将客户端上传的 base64 输出到预览 div,该图像保存为 19k jpg,所以我假设它是 php 脚本。 关于导致数据丢失的原因的任何想法? 也许一些axios 配置值

发生的事情是,前端正在发送 base64 编码的二进制图像数据库。

目前,您正在解码图像,创建一个新图像并将其保存为 jpg。 那只会再次压缩图像。

如果您只是对数据进行解码并将其保存到文件中(使用 .jpg 扩展名),您将获得上传图像的精确副本。

incoming = json_decode(file_get_contents('php://input'))->main;
$mainImage = str_replace('data:image/jpeg;base64,', '', $incoming);
file_put_contents('./uploaded.jpg', base64_decode($mainImage));

您不需要使用 imagecreatefromstring。

JS

$.ajax({
    url: 'URL',
    type: "POST",
    processData: false,
    contentType: 'application/octet-stream',
    timeout: 120*1000,
    crossDomain: true,
    xhrFields: {withCredentials: true},
    data: base64Img,
    success: function (d) {
        console.log('Done!');
    }
})

PHP

$img = file_get_contents('php://input');

if (preg_match('/^data:image\/(\w+);base64,/', $img, $fileExt)) {
    $img = substr($img, strpos($img, ',') + 1);
    $fileExt = strtolower($fileExt[1]); // jpg, png, gif

    if (!in_array($fileExt, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    if ($img === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}
file_put_contents( 'filename.'.$fileExt, base64_decode($img) );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM