|Written by Ian Elliot|
|Monday, 19 August 2013|
Page 3 of 4
Converting From Bitmap To ImageData
The first thing we need is an ImageData object but this can only be created from a Canvas object. In most cases it would be more efficient to generate the ImageData object using any canvas object that was already created in the page but in this case let's create a temporary Canvas object just for this function to use:
Notice that the Canvas object isn't added to the DOM - it isn't displayed just used to create an ImageData object of the correct size. The Width and Height variables are created because they are going to be used in a for loop and it is clearer and more efficient to cache the references in this way. We also need some other data:
Now we can start to transfer the pixel data from the bitmap object to the ImageData object. The data property takes the form of an array of RGBA values with four array element to one pixel. So the first pixel is stored as data, data, data and data as Red, Green, Blue, Alpha values. The data in the bitmap object is stored as BGR with no Alpha value. That is its first pixel is stored in bmpdata, bmpdata and bmpdata as Blue, Green and Red.
Clearly we are going to have to do some re-ordering of values as the pixels are transferred.
We also have the problem that the ImageData has a stride in bytes equal to the row size*4 but the bitmap data could have a stride in bytes equal to the row size *3 rounded up to a multiple of four.
Add to this the fact that the the rows are stored starting from the top of the image in the BMP and from the bottom in the ImageData and you can see that it is very tricky to keep track of everything.
we are going to have to keep track of where we are in each array separately.
The pixel at x,y is stored starting at
in the ImageData and at
in the BMP.
Putting all of this together we get:
Is there an easier way to do this?
Now we have the data stored in the ImageData object which can be returned as the result of the function:
Trying it out
Now we have an ImageData object the BMP can, at last be displayed in a Canvas element.
All we need is a suitable Canvas element:
And at the start of the script we need to add:
The imageData is stored in the canvas as part of the processImage
Of course you may also have to change the size of the Canvas element to show the bitmap off.
An interesting project would be to convert the data to a data URL which could then be loaded as a standard IMG tag.
To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.
|Last Updated ( Tuesday, 27 August 2013 )|