Read image pixels

强颜欢笑 提交于 2019-12-30 07:18:06

问题


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)


回答1:


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

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

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

  • width
  • height
  • data (CanvasPixelArray)

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.

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.

You can create a new empty ImageData object with:

context.createImageData(cssWidth, cssHeight)

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".

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.



来源:https://stackoverflow.com/questions/9429882/read-image-pixels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!