我的图像到数据uri会损坏图像

时间:2015-02-15 19:33:18

标签: javascript jquery image data-uri

我有这张图片:enter image description here

使用此代码(在图像的每个功能中):

    var image = new Image();
    var canvas = document.createElement("canvas"),
      canvasContext = canvas.getContext("2d");
    image.src = $(this).attr("src");
    canvas.width = image.width;
    canvas.height = image.height;
    canvasContext.drawImage(image, 0, 0, image.width, image.height);
    var dataURL = canvas.toDataURL("image/jpeg");

我明白了:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAAnAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRA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W5XUdc1Nkn1fUtm0TOgIWOMHkRIGYKDySWY4zgfl/4u8I+I7rxdr00GmM6HVbwA+dGOk7g9W9RRRXp53RhQp0oU9Er/ofl/gvxHmGMzLM8yxU+erV9m5N+s9krWSVklskkkdBB4Y1wfBC/sf7PPnnxhZsF82PoLC4PXdjoc1q/CH9k74rfF/UY10+ytNL0hXAutUurqNlhBIztiRi7tjOBgAnqwFFFcWCwkMRXhTm3Zq597xfxzmfDeTYvG4FQ9pz7tN25lFXSva66Xuu6Z+nXwp+GHhj4P+BtO8B+Fom+yWKlnmmOZbmZjmSZyP4mPPoBgDAAFFFFfXwSpxUIqyR/G+KxFbMK88XiZuVSbcpN7tt3bfqf/9k=

但这很糟糕,如果我在线转换它我会得到:

Much better quality

这里的质量非常完美。我的代码出了什么问题?我得到的数据更短了。

我添加了var dataURL = canvas.toDataURL("image/jpeg", 1.0);质量,它在Chrome中运行良好。但在IE中它更好,但仍然非常糟糕。 http://ctrlv.cz/shots/2015/02/16/lx1J.png 左:Chrome,右:IE 11.这是一种如何在IE 11中改进它的方法吗?

1 个答案:

答案 0 :(得分:3)

根据HTMLCanvasElement.toDataURL的{​​{3}},您可以提供第二个控制质量的参数,即01之间的数字。

所以试试:

var dataURL = canvas.toDataURL("image/jpeg", 1.0);

并查看质量是否足够好,但由于1.0等于"完整"质量,我希望它看起来与你在画布上看到的完全一样。

注意:如果第二个参数不是Number0之间的1,则浏览器特定的默认值将用于质量。我不确定任何浏览器的价值是什么,但根据MDN documentation,Chrome和Firefox都使用0.92