I am trying to apply a simple relief (emboss-like) effect to an image in a WinForms application using Bitmap.GetPixel and SetPixel.
The idea is to compare the brightness of the current pixel with a shifted pixel (offset by 5 pixels) and compute a new grayscale value.
Here is my code:
public static void ApplyReliefEffect(Form form)
{
if (ImageStorage.bitmap != null)
{
int brightness;
int brightness1;
int brightness2;
Bitmap sourceBitmap = new Bitmap(ImageStorage.bitmap);
Bitmap offsetBitmap = new Bitmap(ImageStorage.bitmap);
Color currentPixel;
Color offsetPixel;
Graphics graphics = form.CreateGraphics();
for (int x = 5; x < sourceBitmap.Width; x++)
{
for (int y = 5; y < sourceBitmap.Height; y++)
{
currentPixel = sourceBitmap.GetPixel(x, y);
offsetPixel = offsetBitmap.GetPixel(x - 5, y - 5);
brightness1 = CalculateBrightness(currentPixel);
brightness2 = CalculateBrightness(offsetPixel);
brightness = 150 + (brightness2 - brightness1);
if (brightness < 0)
{
brightness = 0;
}
else if (brightness > 255)
{
brightness = 255;
}
sourceBitmap.SetPixel(x, y, Color.FromArgb(brightness, brightness, brightness));
}
}
graphics.DrawImage(sourceBitmap, 25, 50);
graphics.Dispose();
}
}
AI tried to tell me like a million times, that this is crazily unoptimal way to do it, and it suggests to use LockBits instead. What I dont understand though is, what makes this so slow? I dont understand the difference between the two (and boy did I try to understand :D). Could you maybe help out please? Thanks in advance!