最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I accesschange pixels in a javascript image object? - Stack Overflow

programmeradmin0浏览0评论

I'm drawing an image to a canvas for display on a web page. I have two copies of the image. The first is the original or ground-truth and the second is a copy that will have various image processing algorithms applied to it.

How can I copy the pixels from the ground-truth image to the copy and how can I access the pixels in the copy to process the image once I've copied it?

Examples I've seen so far all involve accessing and manipulating a canvas object rather than image data. Is this the remended solution? Draw the original image to a canvas and then process the canvas?

I'm drawing an image to a canvas for display on a web page. I have two copies of the image. The first is the original or ground-truth and the second is a copy that will have various image processing algorithms applied to it.

How can I copy the pixels from the ground-truth image to the copy and how can I access the pixels in the copy to process the image once I've copied it?

Examples I've seen so far all involve accessing and manipulating a canvas object rather than image data. Is this the remended solution? Draw the original image to a canvas and then process the canvas?

Share Improve this question asked May 26, 2015 at 8:45 RobinsonRobinson 10.1k16 gold badges79 silver badges121 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

To get the image data use getImageData() method of the canvas context and then access the pixel data from the data property. Each pixel in the data property contains the red, green, blue and alpha channel. So if you did draw your image on to the canvas you could then do

var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
var data = imageData.data;

Then you could pick out specific pixel data from x and y coordinates like so

// pick out pixel data from x, y coordinate
var x = 20;
var y = 20;
var red = data[((imageWidth * y) + x) * 4];
var green = data[((imageWidth * y) + x) * 4 + 1];
var blue = data[((imageWidth * y) + x) * 4 + 2];
var alpha = data[((imageWidth * y) + x) * 4 + 3];

You can find more information on how to work with image data using canvas right here.

Hope that helps.

发布评论

评论列表(0)

  1. 暂无评论