How can I create a 256×256 color space image using graphics draw? Currently I’m using pointers to loop through each pixel location and setting it. Blue goes from 0…255 on X and Green goes from 0…255 on Y. The image is initialized as so.
Bitmap image = new Bitmap(256, 256);
imageData = image.LockBits(new Rectangle(0, 0, 256, 256),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
for (int row = 0; row < 256; row++)
{
byte* ptr = (byte*)imageData.Scan0 + (row * 768);
for (int col = 0; col < 256; col++)
{
ptr[col * 3] = (byte)col;
ptr[col * 3 + 1] = (byte)(255 - row);
ptr[col * 3 + 2] = 0;
}
}
I have a slider that goes 0…255 on Red. On each scroll, it goes through this loop and updates the image.
for (int row = 0; row < 256; row++)
{
byte* ptr = (byte*)imageData.Scan0 + (row * 768);
for (int col = 0; col < 256; col++)
{
ptr[col * 3 + 2] = (byte)trackBar1.Value;
}
}
I’ve figured out how to use a ColorMatrix instead for the scrolling part but how can I initialize the image without using pointers or SetPixel?
First of all, add PictureBox control to the Form.
Then, this code will assign different color to each pixel based on the index in the loop and assign the image to the control:
For some reason there’s no
SetPixelorDrawPixellike I expected, but theFillRectanglewill do exactly the same thing when you give it 1×1 dimensions to fill.Note that it will work fine for small images but the larger the image the slower it will be.