duancaishun4812 2017-03-13 07:32
浏览 25
已采纳

上载的画布图像比其主要源大得多

<img id='imgt' src='01.jpg' alt='img'>

this image is in original 4000x3000px - 0.9MB - computed by css on 960x540px

js

    var img = document.getElementById("imgt");
    c1 = document.createElement("canvas");
    var ctx = c1.getContext("2d");

    var a = $('#imgt').width();
    var b = $('#imgt').height();

    c1.width = a;
    c1.height = b;
    ctx.drawImage(img, 0, 0, a, b);

    var dataURL = c1.toDataURL();
    $.ajax({
      url: 'process.php',
      type: 'post',
      data: {'imgBase64': dataURL},
      success: function(data) {
        console.log('ok');
    }
});

process.php

$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'photo.jpg';
file_put_contents($fileName, $fileData);

Starting image imgt is 4000x3000px - 0.9MB. Resulting image photo.jpg is 960x540px - 1.05MB

I suspect that the resulting image is not jpg but png in fact, so I tried in js instead of var dataURL = c1.toDataURL():

var dataURL = c1.toDataURL("image/jpeg");

also

var dataURL = c1.toDataURL("image/jpeg", 0.95);

In both cases resulting image is about 200KB but not readable in img viewer - it reports damaged image or something like that.

Any help?

  • 写回答

1条回答 默认 最新

  • doulian8485 2017-03-13 10:28
    关注

    Your suspicion was right. When you use only var dataURL = c1.toDataURL(); the image is saved as png by default. To save the image as jpeg with reduced quality (size), you do need to use var dataURL = c1.toDataURL("image/jpeg", 0.95);. But the actual issue occurred when you tried to parse / decode the image on the server side. You were trying to replace data:image/png;base64,, which is only applicable when the image is in png format. Since you're trying to save the image as jpeg hence, you need to use data:image/jpeg;base64,. So, the server side code would be ...

    $img = $_POST['imgBase64'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $fileData = base64_decode($img);
    $fileName = 'photo.jpg';
    file_put_contents($fileName, $fileData);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端