I am having such kind of problem. I am making a small photo editor, where you can select image, change brightness contrast of the image, draw text on the image.
This is the Form.
.
I have this methods.
private void DrawText(string text, int x, int y)
{
RectangleF rectf = new RectangleF(x, y, 90, 50);
Graphics g = Graphics.FromImage(this.pictureBox1.Image);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(text.ToString(), new Font("Tahoma", Convert.ToInt32(this.textBoxSize.Text.ToString())), Brushes.Black, rectf);
g.Flush();
}
private void SetBrightness(int brightness)
{
if (!object.ReferenceEquals(this.pictureBox1.Image, null))
{
Bitmap temp = (Bitmap)this.pictureBox1.Image;
Bitmap bmap = (Bitmap)temp.Clone();
if (brightness < -255) brightness = -255;
if (brightness > 255) brightness = 255;
Color c;
for (int i = 0; i < bmap.Width; i++)
{
for (int j = 0; j < bmap.Height; j++)
{
c = bmap.GetPixel(i, j);
int cR = c.R + brightness;
int cG = c.G + brightness;
int cB = c.B + brightness;
if (cR < 0) cR = 1;
if (cR > 255) cR = 255;
if (cG < 0) cG = 1;
if (cG > 255) cG = 255;
if (cB < 0) cB = 1;
if (cB > 255) cB = 255;
bmap.SetPixel(i, j,
Color.FromArgb((byte)cR, (byte)cG, (byte)cB));
}
}
this.pictureBox1.Image = (Bitmap)bmap.Clone();
}
}
public void SetContrast(double contrast)
{
if (!object.ReferenceEquals(this.pictureBox1.Image, null))
{
Bitmap temp = (Bitmap)this.pictureBox1.Image;
Bitmap bmap = (Bitmap)temp.Clone();
if (contrast < -100) contrast = -100;
if (contrast > 100) contrast = 100;
contrast = (100.0 + contrast) / 100.0;
contrast *= contrast;
Color c;
for (int i = 0; i < bmap.Width; i++)
{
for (int j = 0; j < bmap.Height; j++)
{
c = bmap.GetPixel(i, j);
double pR = c.R / 255.0;
pR -= 0.5;
pR *= contrast;
pR += 0.5;
pR *= 255;
if (pR < 0) pR = 0;
if (pR > 255) pR = 255;
double pG = c.G / 255.0;
pG -= 0.5;
pG *= contrast;
pG += 0.5;
pG *= 255;
if (pG < 0) pG = 0;
if (pG > 255) pG = 255;
double pB = c.B / 255.0;
pB -= 0.5;
pB *= contrast;
pB += 0.5;
pB *= 255;
if (pB < 0) pB = 0;
if (pB > 255) pB = 255;
bmap.SetPixel(i, j,
Color.FromArgb((byte)pR, (byte)pG, (byte)pB));
}
}
this.pictureBox1.Image = (Bitmap)bmap.Clone();
}
}
And on my button CLick I am just calling this methods to do the work. What is the problem when I Draw the text for second time, it is not deleting and drawing text again, but I need the text to be drawn at different location every time and not over the old text. Can you please suggest any solution to this ? Thanks
There are two solutions:
Do not draw on the bitmap; instead draw on a transparent bitmap that is on top of it.
Keep the original Bitmap and copy it just before drawing on it.
Once you have changed the pixels of a bitmap you cannot undo that unless you keep the original data.