GetPixel / SetPixel Operations Are Very Slow & Eventually Runs Out of Memory

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have created a small project in order to learn how to manipulate images. I have a form with a
<a title="ZoomPicBox http://www.bobpowell.net/zoompicbox.htm" target="_blank
ZoomPicBox into which is inserted an image from a bitonal single page TIFF file. The image contains 2550 X 3350 pixels. In code, I convert the ZoomPicBox.Image to a bitmap in order to do GetPixels and SetPixels in an "for" loop.
The goal was to test the color and change the image to a negative image of itself. If the pixel is white, change it to black. If it is black, change it to white. It worked up until the point of running out of memory after just over 1.4
million pixels were converted out of over 8.4 million pixels in the image.
I obviously do not understand the use of images in memory, so I have some basic questions: 1. Why are the GetPixel and SetPixel methods so slooooooow? and what is an alternative approach? 2. Why did it run out of memory, and how can I get around that
problem? What approach should I use? This one puzzles me the most because the control has no problem displaying the 2550 X 3350 image.
<pre lang="x-c# myBitmap = new Bitmap(zoomPicBox2.Image);
Color myColor = new Color();
myColor = Color.Black;
for (y = 0; y <= myBitmap.Height - 1; y++)
{
for (x = 0; x <= myBitmap.Width - 1; x++)
{
Color pixelColor = myBitmap.GetPixel(x, y);

if (pixelColor.R == 0 && pixelColor.B == 0 && pixelColor.G == 0)
{
myBitmap.SetPixel(x, y, Color.White);
}
else
{
myBitmap.SetPixel(x, y, myColor);
}
}
}
zoomPicBox2.Image = myBitmap;
zoomPicBox2.Refresh();[/code]
<
Rob Evans
"... experience trumps brilliance..." Thomas Sowell

View the full article
 
Back
Top