Cast Graphics to Image in C# - c#

I have a pictureBox on a Windows Form.
I do the following to load a PNG file into it.
Bitmap bm = (Bitmap)Image.FromFile("Image.PNG", true);
Bitmap tmp;
public Form1() {
InitializeComponent();
this.tmp = new Bitmap(bm.Width, bm.Height);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawImage(this.bm, new Rectangle(0, 0, tmp.Width, tmp.Height), 0, 0, tmp.Width, tmp.Height, GraphicsUnit.Pixel);
}
However, I need to draw things on the image and then have the result displayed again. Drawing rectangles can only be done via the Graphics class.
I'd need to draw the needed rectangles on the image, make it an instance of the Image class again and save that to this.bm
I can add a button that executes this.pictureBox1.Refresh();, forcing the pictureBox to be painted again, but I can't cast Graphics to Image. Because of that, I can't save the edits to the this.bm bitmap.
That's my problem, and I see no way out.

What you need to do is use the Graphics.FromImage method, which will allow you to draw directly on the image instead of the temporary Graphics object create from within the Paint method:
using (Graphics g = Graphics.FromImage(this.bm))
{
g.DrawRectangle(...);
}
Do this instead of (or in addition to) hooking the Paint method of the PictureBox. This way, you won't need to use a temporary image or Graphics object at all, and when you're finished modifying the original bitmap (this.bm) then you can invoke pictureBox1.Refresh to force the image to be re-displayed.

Related

How to resize a graphic?

I have two pictureBoxes "source" and "dest". Now I would like to resize the "source" image and display it in my "dest"-picturebox.
Question:
How can I resize my "source" image and display it in my "dest"-picturebox?
Here is my code which only display the same image again:
private void pictureBoxZoom_Paint(object sender, PaintEventArgs e)
{
var settings = new Settings();
// Create a local version of the graphics object for the PictureBox.
Graphics Draw = e.Graphics;
Draw.ScaleTransform(2, 2); // rescale by factor 2
IntPtr hDC = Draw.GetHdc(); // Get a handle to pictureBoxZoom.
Draw.ReleaseHdc(hDC); // Release pictureBoxZoom handle.
}
In each case, you have to handle the PictureBox.SizeMode-Property. It determines what the PictureBox does to the image when painting.
If you want to apply a customized Zoom-factor, you can use the Graphics.ScaleTransform-Property. It allows you to scale the complete graphics. The Scaling can be done on the image itself by creating a bitmap (which has a Graphics-object you can use) or by overriding the PictureBox.OnPaint-Method, which requires you to create a class deriving from PictureBox. That's the most flexible attempt because you can control everything by yourself - if you like to.´
EDIT:
Sorry for not being clear enough, the way using the Paint-event does not work. You need to make your own PictureBox-class (derive from PictureBox) and override the OnPaint-method. Then you can call ScaleTransform on the Graphics-object the PictureBox uses. I got a tested sample for you:
public class PictureBoxScaleable : PictureBox
{
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.ScaleTransform(.2f, .2f);
base.OnPaint(pe);
}
}

Convert Graphics object to Bitmap

I do have following issue with my graphics object.
EDIT:
I do have a picturebox_image (imageRxTx) which is a live stream from a camera. What I do in the paint event is to draw some lines on top of the image imageRxTx (not shown in the code below). This works so far without problem.
Now I need to check for circles in imageRxTx and therefore I have to use the method ProcessImage() which needs a Bitmap as parameter. Unfortunately I do not have the Bitmap image but rather the handle (hDC) to my imageRxTx.
Question: How can I get the imageRxTx from my graphics-object and "convert" it to a bitmap-image which I need to use in the method ProcessImage(Bitmap bitmap)? This method needs to be called continously in the paint-event in order to check the live-stream of my camera (imageRxTx).
Here my code:
private void imageRxTx_paint(object sender, PaintEventArgs e)
{
var settings = new Settings();
// Create a local version of the graphics object for the PictureBox.
Graphics Draw = e.Graphics;
IntPtr hDC = Draw.GetHdc(); // Get a handle to image_RxTx.
Draw.ReleaseHdc(hDC); // Release image_RxTx handle.
//Here I need to send the picturebox_image 'image_RxTx' to ProcessImage as Bitmap
AForge.Point center = ProcessImage( ?....? );
}
// Check for circles in the bitmap-image
private AForge.Point ProcessImage(Bitmap bitmap)
{
//at this point I should read the picturebox_image 'image_RxTx'
...
The video image is updated here:
private void timer1_Elapsed(object sender, EventArgs e)
{
// If Live and captured image has changed then update the window
if (PIXCI_LIVE && LastCapturedField != pxd_capturedFieldCount(1))
{
LastCapturedField = pxd_capturedFieldCount(1);
image_RxTx.Invalidate();
}
}
As the title suggests, your main problem is a (common) misconception about what a Graphics object is.
So far I can draw to my graphics object without problem
No! A 'Graphics' object does not contain any graphics. It is only the tool used to draw graphics onto a related Bitmap. So you don't draw onto the Graphics object at all; you use it to draw onto imageRxTx, whatever that is, probably the surface of some Control or Form..
This line is using an often confusing rather useless format of the Bitmap constructor:
Bitmap bmp = new Bitmap(image_RxTx.Width, image_RxTx.Height, Draw);
The last parameter is doing next to nothing; its only function is to copy the Dpi setting. In particular it does not clone or copy any content from 'Draw', which, as you know now, a Graphics object doesn't have anyway, nor any of its other settings. So yes, the bmp Bitmap is still empty after that.
If you want to draw into bmp you need to use a Graphics object that is actually bound to it:
using (Graphics G = Graphics.FromImage(bmp)
{
// draw now..
// to draw an Image img onto the Bitmap use
G.DrawImage(img, ...);
// with the right params for source and destination!
}
None of this should probably happen in the Paint event! But all the preparation code is unclear as to what you really want to do. You should explain just what is the source of the drawing and what is the target!
If instead you want to get the stuff you draw onto image_RxTx into a Bitmap you can use this method somwhere outside (!) the Paint event:
Bitmap bmp = new Bitmap(image_RxTx.Width, image_RxTx.Height);
image_RxTx.DrawToBitmap(bmp, image_RxTx.ClientRectangle);
This will use the Paint event to draw the control into a Bitmap. Not that the result includes the whole PictureBox: The BackgroundImage, the Image and the surface drawing!
Update: To get the combined content of the PictureBox, that is both its Image and what you have drawn onto the surface, you should use the code above (the last 2 lines) in the Tick event of a Timer or right after the line that triggers the Paint event. (You didn't show us how that happens.) You can't acutally put it in the Paint event itself, as it will use the Paint event and therefore would cause an infinite loop!
The method Graphics.CopyFromScreen is probably what you're looking for.
var rect = myControl.DisplayRectangle;
var destBitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format24bppRgb);
using (var gr = Graphics.FromImage(destBitmap))
{
gr.CopyFromScreen(myControl.PointToScreen(new Point(0, 0)), new Point(0, 0), rect.Size);
}

How to keep what is drawn on panel and save to bitmap when the "CLEAR" button is pressed?

I want to finish my paint program for my Daughter and am having issues with the panel keeping drawings rendered on the panel when the application is minimized. I would also like for the program to automatically save to a file what she drew on the panel when she clicks on the "CLEAR" and/or "CLOSE" button.
If you want to keep your drawings you could instead of drawing in the graphics of the panel draw inside a Image of that panel nonetheless you can use Panel.DrawToImage() it should be like this
Panel.DrawToBitmap(Bitmap, Panel.ClientRectangle);
Bitmap bmp; //this will be the image where you would draw to
Graphics g; // the graphics
public ALANA_PAINT()
{
//do your stuff
bmp = new Bitmap(Width,Height)// Initialize the bitmap
Panel.BackgroundImage = bmp;
g = Graphics.FromImage(bmp);
}
//your normal drawing methods
public void Save()
{
bmp.Save(path,imageFormat);
}
For the close function the forms have a FormsClosing event that you could call you save from there
You need to not put the drawing code in pnl1_MouseMove against a new Graphics you get from pnl1.CreateGraphics();. You need to do one of two things.
1) Keep a list of all the "shapes" that need to be drawn and redraw, then subscribe to the event pn1.Paint += pn1_Paint and have that paint method go through the list of all the shapes you have recorded and re draw them
or
2) Don't paint to the Graphics object for the panel, call CreateGraphics on a Bitmap you have in the class then have that bitmap drawn as the background of pn1.
The benefit of method 2 is it will allow most of your code to be the same, you are now just drawing against a bitmap instead of directly against the panel.
you are going to need a method like this one for the 2nd part of your question :
public void SaveBitmap(string location)
{
Bitmap bmp = new Bitmap((int)myPanel.Width, (int)myPanel.Height);
DrawToBitmap(bmp, new Rectangle(0, 0, myPanel.Width, myPanel.Height));
using (FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate))
{
bmp.Save(saveStream, ImageFormat.Bmp);
}
}
If you want to handle it when she closes the window, use the Closing event in the Window.

C# drawing on picturebox, not persistent

I have a List<> object, "imagelist", that contains the paths of many images such as .png's. Now, with the following code:
private void paint_picture(PictureBox picture, string pathofpic)
{
Graphics g = picture.CreateGraphics();
Bitmap drawnpic = null;
if (imagelist.ContainsKey(picture.Name))
{
drawnpic = new Bitmap(pathofpic);
g.DrawImage(drawnpic, 0, 0, picture.Size.Width, picture.Size.Height);
imagelist[picture.Name] = pathofpic;
}
drawnpic.Dispose();
g.Dispose();
}
I call this every time the card's image is changed, but I can't seem to make the image persist on the picturebox, when I drag the picturebox across the form (for example, over other pictureboxes). The click and drag code is just moving the picturebox with the mouse, not really relevant.
I've tried invalidating the form when I de-select the image, but it doesn't do anything.
Is there something I'm missing? Screenshot below, I dragged one image around the form and it overwrote the other images it moved across:
That’s how painting works – you have to handle its Paint event and keep painting the same thing each time it needs repainting.
What you can do is draw on top of your original image:
Bitmap b = new Bitmap(picture.Image);
using (Graphics g = Graphics.FromImage(b)) {
using (Bitmap drawnpic = new Bitmap(pathofpic)) {
g.DrawImage(drawnpic, 0, 0, b.Width, b.Height);
}
}
picture.Image = b;
Then you’d save the original image somewhere and probably use it instead of picture.Image in the new Bitmap line.
And PascalCase for method names, please. ;)

Getting the image in a PictureBox control with the lines drawn using a graphics object

I have troubles understanding how the graphics objects are drawn. Suppose to have this function:
private void DrawLineOnOverlay()
{
using (var g = pictureBox.CreateGraphics())
{
g.DrawLine(OverlayPen, cursorStartx, cursorStarty, cursorEndx, cursorEndy);
}
}
to draw simple lines in a pictureBox control where you have already done this:
pictureBox.Image = BitmapToBeLoaded; // Load an 8-bit indexed Bitmap
My understanding is that both the image loaded and the pixel drawn using the graphics object are parte of the very same image: pictureBox.Image
but this:
Bitmap graphic = pictureBox.Image;
if (graphic != null )
{
graphic = new Bitmap (pictureBox.Image);
graphic.Save( "C:\\packed.png", ImageFormat.Png);
}
does not work: the image saved does not show the lines drawn in red over the image. Why this? What is wrong?
If you want to be able to save your drawings then you need to draw them on a surface and then save the surface. Usually, drawing on PictureBox canvas would not let you save the image because the Image class has nothing to do with drawings. Image is just an abstract class on top of Bitmap which is able to load a GDI+ supported image file and then present it in PictureBox. Drawings are done on a GDI+ drawing surface which is Graphics object.
You can create a surface:
Bitmap surface = new Bitmap(640, 480);
Graphics g = Graphics.FromImage(surface);
using (var OverlayPen = new Pen(Color.Red))
{
g.DrawLine(OverlayPen, cursorStartx, cursorStarty, cursorEndx, cursorEndy);
}
If you want to show drawings, you can set Surface as PictureBox's image. And remember to use using pattern when you are creating graphical objects like pens or brushes because if you don't they're going to stay on memory all the way to the end of the context and they may cause overflow at some points.
To save then:
surface.Save( "C:\\packed.png", ImageFormat.Png);

Categories