编程语言
首页 > 编程语言> > javascript – 为什么用图像绘制的画布颜色与图像本身略有不同?

javascript – 为什么用图像绘制的画布颜色与图像本身略有不同?

作者:互联网

我正在将图像绘制到HTML画布并从中获取图像数据以查找特定像素的颜色.图像是每个国家/地区颜色不同的地图.我想将.getImageData()返回的颜色交叉引用到我手工制作的颜色列表中,以查找任何给定像素所在的国家/地区.

我的问题是,我在画布上绘制的图像和绘制的图像颜色略有不同.

这是绘制到画布的原始图片:

这是我将画布下载为PNG时得到的图片:

这两个看起来几乎相同,但是如果你下载并在照片编辑软件中打开它们,你会发现它们不是.例如,顶部图片中的灰色海洋为73,73,73,255,底部图片中的灰色海洋为71,71,71,255.

我仍然可以完成确定像素所在国家的目标,但是我需要根据我在画布上绘制后下载的图片制作一个新列表.

这似乎是一个非常奇怪的问题.

如果有人想知道,我的代码看起来像这样:

HTML:

<img scr="active_map.png" class="active" id="activeImage">
<canvas id="activeCanvas" width="439px" height="245px">Your Browser Doesn't Support HTML5 Canvases... Sorry :( </canvas>

JS:

var activeCanvas = document.getElementById('activeCanvas')
var activeContext = activeCanvas.getContext("2d");
var activeImage = document.getElementById('activeImage')
activeContext.drawImage(activeImage,0,0);
var activePixelData = activeContext.getImageData(0,0,439,245)["data"];

另外,我使用的是Firefox 31 for Ubuntu

-谢谢您的帮助

解决方法:

正如@GameAlchemist所提到的,您正在使用的PNG存在潜在的伽马校正问题,即RGB值不会被一致地解释.

Henri Sivonen的The Sad Story of PNG Gamma “Correction”提供了非常彻底的分析.简而言之:

In order to compensate for the different gammas, the display gamma of the system an image was authored on and the display gamma of the system where the image is being displayed both need to be known to the piece of software displaying the image. The PNG format provides a means for storing the (reciprocal of) display gamma of the authoring system to the image file. It is up to the program writing the file to store the native display gamma of the image, and then it is up to program displaying the file to compensate.

他建议使用Pngcrush删除可能导致此不一致的颜色配置文件.我已经确认他的技术(pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile.png outfile.png)确实有效.这是你修改过的图片:

你会发现它小了6KB.我已经确认这在Firefox之前和之后的预期工作(从RGB值71,71,71到73,73,73的值).

标签:javascript,html5,canvas,html,getimagedata
来源: https://codeday.me/bug/20190609/1206343.html