bitmap won't appear in form - c#

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.

Related

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();

how to draw a part of a png image c#

I'm trying to draw a part of a .png image but the code i found is not working. this is my code
//define canvas
canvas = pb.CreateGraphics();
sPicture = new Bitmap(pb.Width, pb.Height);
sCanvas = Graphics.FromImage(sPicture);
// Create a Bitmap object from a file.
Image image = Image.FromFile(#"");
// Clone a portion of the Bitmap object.
Rectangle cloneRect = new Rectangle(0, 0, 11, 6);
System.Drawing.Imaging.PixelFormat format =
image.PixelFormat;
Image cloneBitmap = image.Clone(cloneRect, format); //Error: No overload for method 'Clone' takes2 arguments
// Draw the cloned portion of the Bitmap object.
canvas.DrawImage(cloneBitmap, 0, 0);
This is for a sprite sheet and thanks.
You don't need to use Clone(), you can do this directly with Graphics.DrawImage(). It looks like you are trying to do this in WinForms. If, so handle OnPaint for the control you want to draw on. In the example below I'm drawing directly on the form.
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
int width = 60;
int height = 60;
// Create a Bitmap object from a file.
Image sourceImage = Image.FromFile(#"C:\Users\Mike\Downloads\logo.png");
// Draw a portion of the source image.
Rectangle sourceRect = new Rectangle(0, 0, width, height);
graphics.DrawImage(sourceImage, 0, 0, sourceRect, GraphicsUnit.Pixel);
}
If you want to do this without WinForms, there is the extra step of creating the target Graphics instance.
int width = 60;
int height = 60;
// Create a Bitmap object from a file.
Image sourceImage = Image.FromFile(#"C:\Users\Mike\Downloads\logo.png");
// Create a drawing target
Bitmap bitmap = new Bitmap(width, height, sourceImage.PixelFormat);
Graphics graphics = Graphics.FromImage(bitmap);
// Draw a portion of the source image.
Rectangle sourceRect = new Rectangle(0, 0, width, height);
graphics.DrawImage(sourceImage, 0, 0, sourceRect, GraphicsUnit.Pixel);
// Save
bitmap.Save(#"C:\Users\Mike\Downloads\out.png");

Composition from multiple images using C#.NET

I have a PictureBox on which images from files are painted, one on top of another (like a photoshop layering concept, if you're familiar). Being PNGs and with a opacity index, these images are perfect candidates for a image composition. But I can't figure out how to do that and save to a file.
In the following code sample, I've loaded two PNG images into bitmap objects and had them painted on the PictureBox.
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Rectangle DesRec = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
Bitmap bmp;
Rectangle SrcRec;
bmp = (Bitmap)Image.FromFile(Application.StartupPath + "\\Res\\base.png");
SrcRec = new Rectangle(0, 0, bmp.Width, bmp.Height);
e.Graphics.DrawImage(bmp, DesRec, SrcRec, GraphicsUnit.Pixel);
bmp = (Bitmap)Image.FromFile(Application.StartupPath + "\\Res\\layer1.png");
SrcRec = new Rectangle(0, 0, bmp.Width, bmp.Height);
e.Graphics.DrawImage(bmp, DesRec, SrcRec, GraphicsUnit.Pixel);
}
How do I save the composition to a file, preferably to another PNG file?
I would start drawing to an intermediate in-memory bitmap, which I would then save (and eventually draw in your picture box, if really needed). Something like this:
var bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using (var graphics = Graphics.FromImage(bmp))
{
// ...
graphics.DrawImage(...);
// ...
}
bmp.Save("c:\\test.png", ImageFormat.Png);
Thanks both of you. I've decided to do as Efran Cobisi suggested and changed the program so that it does the composing in memory first. Then I can use it where ever and however I want.
My new code to reflect the changes is as follows-
// Image objects to act as layers (which will hold the images to be composed)
Image Layer0 = new Bitmap(Application.StartupPath + "\\Res\\base.png");
Image Layer1 = new Bitmap(Application.StartupPath + "\\Res\\layer1.png");
//Creating the Canvas to draw on (I'll be saving/using this)
Image Canvas = new Bitmap(222, 225);
//Frame to define the dimentions
Rectangle Frame = new Rectangle(0, 0, 222, 225);
//To do drawing and stuffs
Graphics Artist = Graphics.FromImage(Canvas);
//Draw the layers on Canvas
Artist.DrawImage(Layer0, Frame, Frame, GraphicsUnit.Pixel);
Artist.DrawImage(Layer1, Frame, Frame, GraphicsUnit.Pixel);
//Free up resources when required
Artist.dispose();
//Show the Canvas in a PictureBox
pictureBox1.Image = Canvas;
//Save the Canvas image
Canvas.Save("MYIMG.PNG", ImageFormat.Png);
Apparently, the images (Canvas) are being saved with opacity index intact.

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);

Convert Image to Graphic in 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.

Categories