【问题标题】:base64 image to imagecreatefromstring() losing database64 图像到 imagecreatefromstring() 丢失数据
【发布时间】:2017-02-22 07:47:44
【问题描述】:

我正在使用 axios 通过 ajax 发送 base64 字符串。使用下面的方法,当它从base64数据编码回jpg时,我会以某种方式丢失很多数据。如何发送而不丢失数据?

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

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

base64 字符串作为 ajax 和 axios as 发送

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 config value

【问题讨论】:

  • 只需将base64_decode($mainImage)的结果直接保存在一个文件中,例如:file_put_contents('./uploaded.jpg', base64_decode($mainImage));。目前,您正在创建一个新的 Jpeg 图像,当您保存它时会稍微压缩。
  • @MagnusEriksson 我必须将它作为 jpg 保存在服务器上。我猜 axios 正在发送我的 base64 数据字符串,但我不知道。我的目标是使用 ajax 在服务器上获取 jpg,因此任何不会丢失数据的方式都会很好。
  • 试试上面的解决方案。发生的情况是,前端正在发送经过 base64 编码的二进制图像数据库。如果您只是对其进行解码并将其保存到文件中(使用.jpg-extension,如我的示例),您将获得上传图像的精确副本。
  • @MagnusEriksson 哟,工作!天哪,我经历了如此多的编码和解码才能让这个甚至上传我想我错过了一个更直接的解决方案。如果你喜欢,请在下面粘贴,以便我标记为答案。非常感谢。

标签: javascript php base64 filereader axios


【解决方案1】:

发生的情况是,前端正在发送经过 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));

【讨论】:

    【解决方案2】:

    您不需要使用 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) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多