Clear A Bitmap in .Net - c#

I'm using PictureBox control to draw complicated charts, and to optimize for performance i use a cache Bitmap for each layer of the drawing, and draw them on the control image, the upper layers have transparent backgrounds, i need to clear them and redraw on every change.
Assuming g instance of Graphics class of the Bitmap, using g.Clear(Color.White) draws a white rectangle over everything and so hiding lower layers, and g.Clear(Color.Transparent) draws Transparent rectangle over, what means doing nothing.
Isn't there a way to clear the Bitmap returning it to its original state?

private void btn_CancelImage_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Cancel and delete this Image?", "Cancel", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
ClearImage();
pictureBox1.Refresh();
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
public void ClearImage()
{
Graphics g = Graphics.FromImage(ImageBitmap);
g.Clear(Color.White);
}

This is maybe not the answer you were looking for but I think it is an insteresting alternative to what you have.
Instead of having to draw all the layers upwards from every change, I stack as many layers on top of each other by nesting a number of PictureBoxes into one bottom PictureBox pBox0:
List<PictureBox> Layers = new List<PictureBox>();
private void Form1_Load(object sender, EventArgs e)
{
Layers.Add(pBox0);
setUpLayers(pBox0 , 20); // stacking 20 layers onto the botton one
timer1.Start(); // simulate changes
}
The stacking is set up like this:
void setUpLayers(Control parent, int count)
{
for (int i = 0; i < count; i++)
{
PictureBox pb = new PictureBox();
pb.BorderStyle = BorderStyle.None;
pb.Size = parent.ClientSize;
Bitmap bmp = new Bitmap(pb.Size.Width,pb.Size.Height,PixelFormat.Format32bppPArgb);
pb.Image = bmp;
pb.Parent = i == 0 ? pBox0 : Layers[i - 1];
Layers.Add(pb);
}
}
For best performance I use Format32bppPArgb as the pixel format.
For testing I run a Tick event that randomly draws onto a layer:
Random R = new Random(9);
private void timer1_Tick(object sender, EventArgs e)
{
int l = R.Next(Layers.Count-1) + 1;
Bitmap bmp = (Bitmap) Layers[l].Image;
using (Graphics G = Graphics.FromImage(Layers[l].Image))
{
G.Clear(Color.Transparent);
using (Font font = new Font("Consolas", 33f))
G.DrawString(l + " " + DateTime.Now.Second , font, Brushes.Gold,
R.Next(bmp.Size.Width), R.Next(bmp.Size.Height));
}
Layers[l].Image = bmp;
}
To collect all layers into one Bitmap you would make use of the DrawToBitmap method:
Bitmap GetComposite(Control ctl)
{
Bitmap bmp = new Bitmap(ctl.ClientSize.Width, ctl.ClientSize.Height,
PixelFormat.Format32bppArgb);
ctl.DrawToBitmap(bmp, ctl.ClientRectangle);
return bmp;
}
The result can then be saved or used in any other way..
Note that creating too many layers this way will hit a limit for window handles; I hit that limit at around 90 layers. If you need more that a few dozen layers a more intricate caching strategy is called for..

Related

Why can't it draw a rectangle the opposite way?

So I am trying to recreate the Snipping Tool that comes with Windows.
However I've manage to get it to draw a rectangle from the top left corner and then when I move my cursor to the bottom right.
However if I try to move my cursor from let's say the middle of the screen to the top left it doesnt draw the rectangle.
Why is this?
Here is a GIF showing what happends
https://i.imgur.com/0Y7xXnS.gifv
//These variables control the mouse position
int selectX;
int selectY;
int selectWidth;
int selectHeight;
public Pen selectPen;
//This variable control when you start the right click
bool start;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Hide the Form
this.Hide();
//Create the Bitmap (This is an a black bitmap holding just the size.) (Bitmap is mutable)
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
//Create a graphics object that's ready for alteration. `printscreen` is now a graphics Object
Graphics graphics = Graphics.FromImage(printscreen);
//Alter the graphics object which again is the printscreen
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
//Create a temporary memory stream for the image
using (MemoryStream s = new MemoryStream())
{
//save graphic variable into memory
printscreen.Save(s, ImageFormat.Bmp);
//Set the size of the picturebox
pictureBox1.Size = new Size(Width, Height);
//set the value of the picturebox.Image to an Image.FromStream and load the temp stream
pictureBox1.Image = Image.FromStream(s);
}
//Show Form
this.Show();
//Cross Cursor
Cursor = Cursors.Cross;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
selectX = e.X;
selectY = e.Y;
selectPen = new Pen(Color.DimGray, 1);
selectPen.DashStyle = DashStyle.Solid;
pictureBox1.Refresh();
start = true;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (start)
{
selectWidth = e.X - selectX;
selectHeight = e.Y - selectY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
selectX, selectY, selectWidth, selectHeight);
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Stream sound = Resources.SnapshotSound;
SoundPlayer player = new SoundPlayer(sound);
player.PlaySync();
Application.Exit();
}
}
So what you end up with is basically a rectangle with a negative width and height.
You'll probably want to use the Math.Abs to make sure you get a proper width and height in the cases the difference would become negative.
With that, you will also probably want to draw from different positions based on where your cursor is in relation to the selected point. Something like
selectWidth = e.X - selectX;
selectHeight = e.Y - selectY;
// If width is less than 0, draw from pointer, otherwise from select X
var drawFromX = selectWidth < 0 ? e.X : selectX;
// If height is less than 0, draw from pointer, otherwise from select Y
var drawFromY = selectHeight < 0 ? e.Y : selectY;
pictureBox1.Refresh();
pictureBox1.CreateGraphics().DrawRectangle(selectPen,
drawFromX,
drawFromY,
Math.Abs(selectWidth), // Make sure the rectangle width is positive
Math.Abs(selectHeight)); // Make sure the rectangle height is positive

Refresh does not refresh

I made an user control and I draw a rectangle directly in the window, like this (this is a simplified version):
private int rec_len = 200;
private void Draw_()
{
Pen pn = new Pen( Color.Black, WIDTH_LINE );
Graphics graph = this.CreateGraphics();
graph.Clear( Color.Transparent );
this.Refresh();
graph.DrawRectangle( pn, 20, 10, rec_len, 40 );
this.Refresh();
graph.Dispose();
}
public void button_Build_Click( object sender, EventArgs e )
{ rec_len += 10; Draw_(); }
The strange thing is that the second refresh actually poses a problem: if I comment it out, the rectangle is visible, if I let it in the code, the rectangle is not visible. In the real code I have to draw more than a rectangle and I want the refresh at the end, otherwise the background is visible between the moment I erase old drawing and the moment the new one is ready.
The surface of a control is not stored: When you paint on a control, the drawing is not saved and need to be redrawn each time the control is repainted (After a refresh for example). To create a persistante graphic, you can create a bitmap, draw on the bitmap and assign this bitmap to the BackgroundImage property.
Bitmap bmp = new Bitmap(WIDTH, HEIGHT);
void Initialize()
{
this.BackgroundImage = bmp;
}
private int rec_len = 200;
private void Draw_()
{
Pen pn = new Pen(Color.Black, WIDTH_LINE);
using (Graphics graph = Graphics.FromImage(bmp))
{
graph.Clear(Color.Transparent);
this.Refresh();
graph.DrawRectangle(pn, 20, 10, rec_len, 40);
this.Refresh();
}
}
public void button_Build_Click(object sender, EventArgs e) { rec_len += 10; Draw_(); }

Using control functions in a bitmap in C#

I was thinking of implementing a bitmap into a picturebox (or the otherway round), such that I could have the option to:
1.drag and drop the item (Control function with mousebuttons)
2.rotate the item (bitmap function).
This is what I have currently:
Bitmap bmp = new Bitmap(#"my source");
PictureBox item = new System.Windows.Forms.PictureBox();
I create the picturebox on the click of a button:
private void button2_Click(object sender, EventArgs e)
{
item.BackColor = Color.Blue;
item.Location = new Point(400, 200);
item.MouseDown += new MouseEventHandler(textbox_MouseDown);
item.MouseMove += new MouseEventHandler(textbox_MouseMove);
item.MouseUp += new MouseEventHandler(textbox_MouseUp);
item.MouseWheel += new MouseEventHandler(textbox_MouseWheel);
item.Image = bmp;
item.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(item);
item.BringToFront();
}
and in the textbox_MouseMove void, I try to use the middle button to signal the rotation of the image
void textbox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Middle )
{
if (activeControl == null || activeControl != sender)
{
return;
}
this.Paint += new PaintEventHandler(objectrotation_Paint);
Invalidate();
}
}
where the PaintEvent is responsible for the rotation of the image
private void objectrotation_Paint(object sender, PaintEventArgs d)
{
int dpi = 96;
bmp.SetResolution(dpi, dpi);
if (bmp != null)
{
float bw2 = bmp.Width / 2f;
float bh2 = bmp.Height / 2f;
d.Graphics.TranslateTransform(bw2, bh2);
d.Graphics.RotateTransform(angle);
d.Graphics.TranslateTransform(-bw2, -bh2);
d.Graphics.DrawImage(bmp,0,0);
d.Graphics.ResetTransform();
}
}
This however would create two sets of images, i.e. when I press button 2 I get one image, when I move my mouse with middle button down I get the second image (rotating).Refering to some of the questions on here, people recommend using
item.Image = bmp;
but it simply copies the from picturebox to the bitmap while they have seperate controls. While the picturebox class could not perform rotations without implementing a Bitmap, the Bitmap class does not have the option to perform actions like OnMouseMove etc.
Is there any way to combine my bitmap and the picturebox such that I could achieve my two goals?

Drawing on PictureBox inside of Panel - C#

The question I have here is sort of a 2 parter.
I have a picturebox that is positioned inside of a panel. When I open an image, the picturebox is resized to the size of the image, while the panel stays the same size. The panel just has scrollbars to see the whole image.
There are 2 things going wrong with this.
When I resize the picturebox, for some reason I can only draw in the previous portion of the picturebox. Ex. The imagebox starts out by default as 200x200. I open an image that is 500x400. And I can only still draw in the 200x200 portion of the image.
The second issue that I am having is that when I do draw in that selective portion of the picturebox, when I scroll to where my painting is out of view, and come back, the image that i painted gone. I know there is some sort of picturebox.invalidate() that I need. I am just not sure how to use it.
Here is my code to get a good grasp on what I'm doing.
public Form1()
{
InitializeComponent();
DrawArea = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height );
pictureBox1.Image = DrawArea;
objGraphics = this.pictureBox1.CreateGraphics();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
drawImage(e);
}
public void drawImage(MouseEventArgs e)
{
Rectangle rDraw = new Rectangle();
if (e.Button == MouseButtons.Left)
{
rDraw.X = e.X;
rDraw.Y = e.Y;
rDraw.Width = 3;
rDraw.Height = 3;
objGraphics.DrawEllipse(System.Drawing.Pens.Black, rDraw);
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.bmp)|*.jpg; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
Bitmap bit = new Bitmap(open.FileName);
pictureBox1.Size = bit.Size;
DrawArea = bit;
pictureBox1.Image = bit;
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
Thanks Alot!
You need to draw in the picturebox's Paint event.
You should (almost) never draw on CreateGraphics().

How to save a picturebox control as a jpeg file after it's edited

I have a PictureBox on my Windows Forms application.
I load a picture in it and I have enabled the Paint event in my code. It draws a rectangle.
Like this:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics gr = e.Graphics;
Pen p = new Pen(Color.Red);
p.Width = 5.0f;
gr.DrawRectangle(p, 1, 2, 30, 40);
}
And I click the "save" button:
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(#"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
}
But the saved file never contains the rectangle that I drew.
Does anyone have any idea?
Thanks.Your anwers all helped.
This worked
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.ImageLocation=#"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000.jpg" ;
}
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(#"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(pictureBox1.Image);
Graphics gr = Graphics.FromImage(bmp);
Pen p = new Pen(Color.Red);
p.Width = 5.0f;
gr.DrawRectangle(p, 1, 2, 30, 40);
pictureBox1.Image = bmp;
}
You probably shouldn't draw directly on the PictureBox.
You need to use a Bitmap instead. Try putting the bitmap in the PictureBox.Image and then call Save().
Check this for more details
Here is my solution with additional support to various file types:
public void ExportToBmp(string path)
{
using(var bitmap = new Bitmap(pictureBox.Width, pictureBox.Height))
{
pictureBox.DrawToBitmap(bitmap, pictureBox.ClientRectangle);
ImageFormat imageFormat = null;
var extension = Path.GetExtension(path);
switch (extension)
{
case ".bmp":
imageFormat = ImageFormat.Bmp;
break;
case ".png":
imageFormat = ImageFormat.Png;
break;
case ".jpeg":
case ".jpg":
imageFormat = ImageFormat.Jpeg;
break;
case ".gif":
imageFormat = ImageFormat.Gif;
break;
default:
throw new NotSupportedException("File extension is not supported");
}
bitmap.Save(path, imageFormat);
}
}
Here is a small example that clarified a few things for me (I was struggling with this a bit too).
pBox is a PictureBox on Form1, make it at least 50x50
appPath was derived from System.Reflection but use any path you like
There are two buttons, one for drawing, one for saving, their click events are in the code below.
Things I learned:
(1) "pBox.Image =" doesn't do anything but initialize the pBox image, it DOES NOT have to be a filename as EVERY example I found used (had problem saving to that same file because it was share locked). Also, if your goal is to see things on the entire control's surface, you'll probably like setting the size at initialize time to the size you need. I used the pBox's size in this example but normally I use the bitmap size (because I typically begin with a real picture file).
(2) I always had problems either seeing my draws show up on the control or seeing my changes saved in the output file (or both). In my prior attempts I would duplicate the draws both on the control and on the bitmap. Of course that isn't necessary but the edited bitmap DOES need to be reloaded into the control.image... and THAT was the piece of this puzzle I was missing.
(A) Create a bitmap from the control.image and draw on the bitmap
(B) Load the bitmap into the control.Image (so you can see the changes caused by the draw)
(C) Save the control.Image
(2-option) You have a global (or passed) bitmap (probably from a real file)
(A) Draw on the bitmap
(B) Load the bitmap into the control.Image (so you can see the changes)
(C) Save the bitmap
public Form1()
{
InitializeComponent();
pBox.Image = new Bitmap(pBox.Width, pBox.Height);
}
private void DrawStuff1_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(pBox.Image);
Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(Brushes.Red, 5, 5, 25, 25); //hard-coded size to reduce clutter
pBox.Image = bmp; //this makes your changes visible
}
private void Save_Click(object sender, EventArgs e)
{
pBox.Image.Save(appPath + "SavedImage.bmp");
}
You need paint to image of picture, not to the Graphics control on Paint event.
EDIT:
using( Graphics g = Graphics.FromImage( pictureBox1.Image ) ) {
// there you will be do, what you do in Paint event
}
// ... somewhere else ...
pictureBox1.Save( _required_parameters_ );

Categories