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 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类