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 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);
    
    点赞 评论 复制链接分享

相关推荐