读取图像像素 [英] Read image pixels

查看:100
本文介绍了读取图像像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在画布A中读取图像的像素并在画布B上创建像素?我想在Canvas B上创建新像素,只有图像的像素为绿色。
例如。如果图像的像素(120,45)是绿色的,我需要在Canvas B中创建一个绿色的像素(120,45)

Is it possible to read pixels of an image in canvas A and create pixels on canvas B? And I want to create the new pixels on Canvas B only where the image's pixels are green. eg. If images' pixel (120,45) is green I need to create a green colored pixel in Canvas B at (120,45)

推荐答案

您可以使用 canvas ImageData 获取每个像素的颜色值。函数:

You can use canvas ImageData to get color values for each pixels. The function:

context.getImageData(left, top, width, height);

返回 ImageData 对象,由以下属性组成:

returns an ImageData object, which consists of the following properties:

  • width
  • height
  • data (CanvasPixelArray)

CanvasPixelArray 包含所有像素的RGBA值,从左上角开始向下到右下方。换句话说,它是一个包含 4 * width * height 条目数的数组。

The CanvasPixelArray contains the RGBA values for all the pixels, starting from top-left working its way to bottom-right. So in other words, it is an array containing 4*width*height number of entries.

使用它,你可以开始循环每个像素(每个像素 + = 4 条目),并检查RGBA值。如果它们匹配您想要的特定值,即绿色,那么您将该值复制到画布B,您将通过修改新创建的ImageData对象来创建它。

Using that, you can start looping through each pixel (+=4 entries per pixel), and check the RGBA values. If they match a specific value you want, i.e. green, then you would copy that value to a canvas B, which you would create by modifying a newly created ImageData object.

您可以创建一个新的空ImageData对象:

You can create a new empty ImageData object with:

context.createImageData(cssWidth, cssHeight)

请注意,您需要知道标识绿色的特定RGBA值或定义特定条件,即RGBA的G值是否为> = 150 然后是绿色。

Note that you will need to know specific RGBA values that identify "green" or define specific conditions, i.e. if the G value of RGBA is >= 150 then it is "green".

另请注意,您无法获得 ImageData 已经污染了原产地以外的资源。即,如果您将图像绘制到非CORS安全的画布上,您将无法再从该画布中检索 ImageData ,就像您可以也不要使用 toDataURL

Also note that you cannot get the ImageData that has been tainted resources outside of your origin. i.e., if you draw an image onto the canvas that isn't CORS safe, you won't be able to retrieve the ImageData from that canvas anymore, much like how you can't use toDataURL either.

这篇关于读取图像像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆