Convert Image to Graphic in c# - c#

How to convert Image to Graphic?

You can't convert a Graphics object into an image, as the Graphics object doesn't contain any image data.
The Graphics object is just a tool used to draw on a canvas. That canvas is typically a Bitmap object or the screen.
If the Graphics object is used for drawing on a Bitmap, then you already have the image. If the Graphics object is used for drawing on the screen, you would have to make a screen shot to get an image of the canvas.
If the Graphics object was created from a window control, you could use the control's DrawToBitmap method to render the control on an image instead of on the screen.

You need an Image in order to draw your Graphics on, so you probably already have the image:
Graphics g = Graphics.FromImage(image);

As Darin states, you probably already have the image. If you don't, you can create a new one and draw to that one
Image bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp)) {
// draw in bmp using g
}
bmp.Save(filename);
Save saves the image to a file on your hard drive.

If you're drawing directly on a Control's graphics, you can create a new Bitmap with the same dimensions as the control and then call Control.DrawToBitmap(). However, the better way to go is usually to start with a Bitmap, draw to its graphics (as suggested by Darin), and then paint the bitmap onto the Control.

The best method to turn graphics into a bitmap is to get rid of the 'using' stuff:
Bitmap b1 = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(b1);
g.CopyFromScreen(0, 0, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
b1.Save("screen.bmp");
I discovered this while figuring out how to turn graphics into a bitmap, and it works like a charm.
I have some examples on how to use this:
//1. Take a screenshot
Bitmap b1 = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(b1);
g.CopyFromScreen(0, 0, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
b1.Save("screen.bmp");
//2. Create pixels (stars) at a custom resolution, changing constantly like stars
private void timer1_Tick(object sender, EventArgs e)
{
/*
* Steps to use this code:
* 1. Create new form
* 2. Set form properties to match the settings below:
* AutoSize = true
* AutoSizeMode = GrowAndShrink
* MaximizeBox = false
* MinimizeBox = false
* ShowIcon = false;
*
* 3. Create picture box with these properties:
* Dock = Fill
*
*/
//<Definitions>
Size imageSize = new Size(400, 400);
int minimumStars = 600;
int maximumStars = 800;
//</Definitions>
Random r = new Random();
Bitmap b1 = new Bitmap(imageSize.Width, imageSize.Height);
Graphics g = Graphics.FromImage(b1);
g.Clear(Color.Black);
for (int i = 0; i <r.Next(minimumStars, maximumStars); i++)
{
int x = r.Next(1, imageSize.Width);
int y = r.Next(1, imageSize.Height);
b1.SetPixel(x, y, Color.WhiteSmoke);
}
pictureBox1.Image = b1;
}
With this code, you can use all the commands for the Graphics Class, and copy them to a bitmap, therefore allowing you to save anything designed with the graphics class.
You may use this to your advantage.

Related

image getting blurred when enlarging picture box

I am developing an application for image processing. To zoom the image, I enlarge PictureBox. But after enlarging I get below image as result.
But I want result like below image
Here is my Code :
picturebox1.Size = new Size((int)(height * zoomfactor), (int)
(width* zoomfactor));
this.picturebox1.Refresh();
The PictureBox by itself will always create a nice and smooth version.
To create the effect you want you need to draw zoomed versions yourself. In doing this you need to set the
Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
Then no blurring will happen..
Example:
private void trackBar1_Scroll(object sender, EventArgs e)
{
Bitmap bmp = (Bitmap)pictureBox1.Image;
Size sz = bmp.Size;
Bitmap zoomed = (Bitmap)pictureBox2.Image;
if (zoomed != null) zoomed.Dispose();
float zoom = (float)(trackBar1.Value / 4f + 1);
zoomed = new Bitmap((int)(sz.Width * zoom), (int)(sz.Height * zoom));
using (Graphics g = Graphics.FromImage(zoomed))
{
if (cbx_interpol.Checked) g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.PixelOffsetMode = PixelOffsetMode.Half;
g.DrawImage(bmp, new Rectangle( Point.Empty, zoomed.Size) );
}
pictureBox2.Image = zoomed;
}
Of course you need to avoid setting the PBox to Sizemode Zoom or Stretch!

Cropping Image(From Screen)

I have read many question about this. But my question is little bit different. What i need to do crop image from screen.
There is my codes
Bitmap photo = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.primaryScreen.Bounds.Height)
Graphics gr = Graphics.FromImage(photo);
gr.CopyFromScreen(0,0,0,0 new size(foto.Width,foto.Height));
picturebox1.Image = photo;
And there my crop codes
Rectangle cropRec = new Rectangle(1,1,1,1);
Bitmap target = new Bitmap(cropRec.Width,cropRec.Height);
using(Graphics g = Graphics.FromImage(target))
{
g.DrawImage(photo,new Rentangle(0,0,target.Width,target.Height),cropRec,GraphicsUnit.Pixel);
}
I want to crop middle part of this photo and compare with itself.
Thanks n advance
To symmetrically crop your image as shown in the following sketch, try creating a Bitmap with margins in the X and Y axis and then cropping the screenshot image by using those margins in CopyFromScreen():
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width - 2 * xmargin, Screen.PrimaryScreen.Bounds.Height - 2 * ymargin);
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(xmargin, ymargin, 0, 0, printscreen.Size);

Get bitmap and draw it into image

I am trying to save my drawing from picturebox into bitmap and draw that bitmap into image. So far, nothing has appeared in the final image, but while debugging I can only say, that the original bitmap is not null and with/height are correct. However nothing appears after I draw it into image.
I save my drawing into bitmap like this:
GraphicsPath path = RoundedRectangle.Create(x, y, width, height, corners, RoundedRectangle.RectangleCorners.All);
g.FillPath(Brushes.LightGray, path);
g.SetClip(path);
using (Font f = new Font("Tahoma", 9, FontStyle.Bold))
g.DrawString(mtb_hotspotData.Text, f, Brushes.Black, textX, textY);
g.ResetClip();
bitmap = new Bitmap(width, height, g);
Then save it:
hs.bitmap = new Bitmap(bitmap);
And finally use it:
for (int i = 0; i < imageSequence.Count; i++) {
Graphics g = Graphics.FromImage(imageSequence[i]);
//g.CompositingMode = CompositingMode.SourceOver;
//hotspot.bitmap.MakeTransparent();
int x = hotspot.coordinates[i].X;
int y = hotspot.coordinates[i].Y;
g.DrawImage(hotspot.bitmap, new Point(x, y));
}
return imageSequence;
So far I was not able to find any problem in this solution, therefore I have no idea, where the malfunction is.
You seem to misunderstand the relation of a Bitmap and a Graphics object.
A Graphics object does not contain any graphics; it is a tool used to draw into a bitmap of some sort.
The Bitmap constructor you are using (public Bitmap(int width, int height, Graphics g)) does not really connect the Bitmap and the Graphics object. It only uses the dpi resolution from the Graphics.
You don't show how your Graphics is created. If you want to draw into a Bitmap (as opposed to a control's surface) the most direct way is this:
Bitmap bitmap = new Bitmap(width, height);
bitmap.SetResolution(dpiX, dpiY); // optional
using (Graphics G = Graphics.FromImage(bitmap ))
{
// do the drawing..
// insert all your drawing code here!
}
// now the Bitmap can be saved or cloned..
bitmap.Save(..);
hs.bitmap = new Bitmap(bitmap); // one way..
hs.bitmap = bitmap.Clone(); // ..or the other
// and finally disposed of (!!)
bitmap.Dispose();

bitmap won't appear in form

I am trying to make a bitmap appear in my form, but it won't work.
my code:
private void button2_Click(object sender, EventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Black);
Bitmap bitmap = new Bitmap(1000, 1000);
Graphics gfx = Graphics.FromImage(bitmap);
gfx.Clear(Color.Red);
for (int i = 0; i < 5; i++)
{
gfx.DrawRectangle(pen, i + 50, 50, 50, 50);
}
}
All your code is doing is drawing to a bitmap, in memory. You don't have any code to actually display that bitmap anywhere.
You could modify the code to paint the bitmap onto the form, but as nvoigt suggested in comments, a better solution would be to use a PictureBox control. When you create your bitmap, you can assign that bitmap to the picture box's Image property:
Bitmap bitmap = new Bitmap(1000, 1000);
// render bitmap
pictureBox1.Image = bitmap;
If you absolutely must draw on the form itself, you can override the form's OnPaint method, and use the graphics object's DrawImage() method to render your bitmap there.

C# Graphics shown in Form but not in Bitmap

I'm using C# and I would like to draw some polygons on a Form, then to save the graphics in a Bitmap.
Following this question answers I wrote a method in my Form class:
private void draw_pol()
{
Graphics d = this.CreateGraphics();
// drawing stuff
Bitmap bmp = new Bitmap(this.Width, this.Height, d);
bmp.Save("image.bmp");
}
In this way the Form displays correctly the graphics and the Bitmap file named "image.bmp" is created, but that file is a white image.
Why isn't the bmp file showing any image? What I'm doing wrong?
Thank you very much.
The graphics parameter you are passing to your bitmap is only used to specify the resolution of the bitmap. It does not in any way paint to the bitmap.
from MSDN:
The new Bitmap that this method creates takes its horizontal and vertical resolution from the DpiX and DpiY properties of g, respectively.
Instead, use Graphics.FromImage() to get a Graphics object you can use. Moreover, you should Dispose the Graphics object after painting. This is an ideal usage for the using statement.
Bitmap bmp = new Bitmap(this.Width, this.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
//paint stuff
}
bmp.Save(yourFile);
If you also need to paint this to the form, you can easily just draw the bitmap you created:
Graphics g = this.CreateGraphics();
g.DrawImage(bmp, 0, 0);
A Graphics instance only operates on one Bitmap. It's either the one you want to save, or the one on your form.
You can for example do this to render the drawn bitmap on your form and save it afterwards:
private void DrawOnBitmap()
{
using (var bitmap = new Bitmap(this.Width, this.Height))
{
using (var bitmapGraphics = Graphics.FromImage(bitmap))
{
// Draw on the bitmap
var pen = new Pen(Color.Red);
var rect = new Rectangle(20, 20, 100, 100);
bitmapGraphics.DrawRectangle(pen, rect);
// Display the bitmap on the form
using (var formGraphics = this.CreateGraphics())
{
formGraphics.DrawImage(bitmap, new Point(0, 0));
}
// Save the bitmap
bitmap.Save("image.bmp");
}
}
}
you need a graphics object that represents the bitmap,so that you can draw on image.do lke this:
create the bitmap object
create the graphics object using Graphics.FromImage method
pass bitmap object as argument to graphics object
Bitmap bmp = new Bitmap(this.Width, this.Height, d);
bmp.Save("image.bmp");//for your need
Graphics d=Graphics.FromImage(bmp);

Categories