recently I started working on my project and unfortunately I have a problem. I want to get sqaures 5x5 from one image, count average color of them and then draw a circle to another Bitmap so I can get a result like this http://imageshack.com/a/img924/9093/ldgQAd.jpg
I have it done, but I can't save to file the Graphics object. I've tried many solutions from Stack, but none of them worked for me.
My code:
//GET IMAGE OBJECT
Image img = Image.FromFile(path);
Image newbmp = new Bitmap(img.Width, img.Height);
Size size = img.Size;
//CREATE NEW BITMAP WITH THIS IMAGE
Bitmap bmp = new Bitmap(img);
//CREATE EMPTY BITMAP TO DRAW ON IT
Graphics g = Graphics.FromImage(newbmp);
//DRAWING...
//SAVING TO FILE
Bitmap save = new Bitmap(size.Width, size.Height, g);
g.Dispose();
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
The file 'file.bmp' is just a blank image. What am I doing wrong?
First, your Graphics object should be created from the target bitmap.
Bitmap save = new Bitmap(size.Width, size.Height) ;
Graphics g = Graphics.FromImage(save );
Second, flush your graphics before Save()
g.Flush() ;
And last, Dispose() after Save() (or use a using block)
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
g.Dispose();
It should give you something like this :
Image img = Image.FromFile(path);
Size size = img.Size;
//CREATE EMPTY BITMAP TO DRAW ON IT
using (Bitmap save = new Bitmap(size.Width, size.Height))
{
using (Graphics g = Graphics.FromImage(save))
{
//DRAWING...
//SAVING TO FILE
g.Flush();
save.Save("file.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
}
}
Related
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);
I found code to rotate an image. My problem is that when I save it, the image is already opened, and in use by me (As, I opened it to rotate it).
How can I avoid this?
public static void RotateImage(string filePath, float angle)
{
//create a new empty bitmap to hold rotated image
using (var img = Image.FromFile(filePath))
{
using(var bmp = new Bitmap(img.Width, img.Height))
{
//turn the Bitmap into a Graphics object
Graphics gfx = Graphics.FromImage(bmp);
//now we set the rotation point to the center of our image
gfx.TranslateTransform((float) bmp.Width/2, (float) bmp.Height/2);
//now rotate the image
gfx.RotateTransform(angle);
gfx.TranslateTransform(-(float) bmp.Width/2, -(float) bmp.Height/2);
//set the InterpolationMode to HighQualityBicubic so to ensure a high
//quality image once it is transformed to the specified size
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
//now draw our new image onto the graphics object
gfx.DrawImage(img, new Point(0, 0));
//dispose of our Graphics object
}
img.Save(filePath);
}
edit: Updated code as per Anthony's advice.
edit:
Just some FYI, this was accomplished in a couple of lines...
public static void RotateImage(string filePath, float angle)
{
//create a new empty bitmap to hold rotated image
byte[] byt = System.IO.File.ReadAllBytes(filePath);
var ms = new System.IO.MemoryStream(byt);
using (Image img = Image.FromStream(ms))
{
RotateFlipType r = angle == 90 ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
img.RotateFlip(r);
img.Save(filePath);
}
}
Using your existing code you can do the following:
byte[] byt = System.IO.File.ReadAllBytes(filepath);
System.IO.MemoryStream ms = new System.IO.MemoryStream(byt);
Image img = Image.FromStream(ms);
That will not have the file locked when you go to save it.
I need to stretch various sized bitmaps to fill a PictureBox.
PictureBoxSizeMode.StretchImage sort of does what I need but can't think of a way to properly add text or lines to the image using this method. The image below is a 5x5 pixel Bitmap stretched to a 380x150 PictureBox.
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox.Image = bmp;
I tried adapting this example and this example this way
using (var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height))
using (var g = Graphics.FromImage(bmp2))
{
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
pictureBox.Image = bmp2;
}
but get this
What am I missing?
It appears you're throwing away the bitmap (bmp2) you'd like to see in your picture box! The using block from the example you posted is used because the code no longer needs the Bitmap object after the code returns. In your example you need the Bitmap to hang around, hence no using-block on the bmp2 variable.
The following should work:
using (bmp)
{
var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height);
using (var g = Graphics.FromImage(bmp2))
{
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
pictureBox.Image = bmp2;
}
}
The red X on white background happens when you have an exception in a paint method.
Your error is that you are trying to assign a disposed bitmap as the image source of your picturebox. The use of "using" keyword will dispose the bitmap you are using in the picturebox!
So your exception, i know, will be ObjectDisposedException :)
You should create the bitmap once and keep it until it is not needed anymore.
void ReplaceResizedPictureBoxImage(Bitmap bmp)
{
var oldBitmap = pictureBox.Image;
var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height);
using (var g = Graphics.FromImage(bmp2))
{
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
pictureBox.Image = bmp2;
}
if (oldBitmap != null)
oldBitmap.Dispose();
}
This function will allow you to replace the old bitmap disposing the previous one, if you need to do that to release resources.
What I have is a .tif file being loaded into a picture box. When I try to draw a rectangle on top of that tif it throws the following error:
A Graphics object cannot be created from an image that has an indexed pixel format.
here is the code i'm using, it throws the error at using (Graphics g = Graphics.FromImage(img)). img is the file being loaded into the picture box.
using (Graphics g = Graphics.FromImage(img))
{
int x1value = Convert.ToInt32(x1);
int y1value = Convert.ToInt32(y1);
int x3value = Convert.ToInt32(x3);
int y3value = Convert.ToInt32(y3);
SolidBrush blackBrush = new SolidBrush(Color.Black);
g.FillRectangle(blackBrush, x1value, y1value, x3value, y3value);
Image img = Image.FromFile(string2image);
Bitmap source = (Bitmap)img;
source = new Bitmap(320, 240, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
pictureBox1.Image = source;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
using (Graphics g = Graphics.FromImage(pictureBox1.Image))
This method actually only draws a gaint black box. not causes a blackbox to be written over the original file.
You're trying to get a graphics context from an image. You need to get one from a Bitmap buffer i believe.
I need to add text to an image file. I need to read one image file (jpg,png,gif) and I need add one line text to it.
Well in GDI+ you would read in the file using a Image class and then use the Graphics class to add text to it. Something like:
Image image = Image.FromFile(#"c:\somepic.gif"); //or .jpg, etc...
Graphics graphics = Graphics.FromImage(image);
graphics.DrawString("Hello", this.Font, Brushes.Black, 0, 0);
If you want to save the file over the old one, the code has to change a bit as the Image.FromFile() method locks the file until it's disposed. The following is what I came up with:
FileStream fs = new FileStream(#"c:\somepic.gif", FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(fs);
fs.Close();
Bitmap b = new Bitmap(image);
Graphics graphics = Graphics.FromImage(b);
graphics.DrawString("Hello", this.Font, Brushes.Black, 0, 0);
b.Save(#"c:\somepic.gif", image.RawFormat);
image.Dispose();
b.Dispose();
I would test this quite thoroughly though :)
Specifically for gifs to have a gif result, you should write on each frame like the following:
string originalImgPath = #"C:\test.gif";
Image IMG = Image.FromFile(originalImgPath);
FrameDimension dimension = new FrameDimension(IMG.FrameDimensionsList[0]);
int frameCount = IMG.GetFrameCount(dimension);
int Length = frameCount;
GifBitmapEncoder gEnc = new GifBitmapEncoder();
for (int i = 0; i < Length; i++)
{
// Get each frame
IMG.SelectActiveFrame(dimension, i);
var aFrame = new Bitmap(IMG);
// write one the selected frame
Graphics graphics = Graphics.FromImage(aFrame);
graphics.DrawString("Hello", new Font("Arial", 24, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, 50, 50);
var bmp = aFrame.GetHbitmap();
var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmp,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
// merge frames
gEnc.Frames.Add(BitmapFrame.Create(src));
}
string saveImgFile = #"C:\modified_test.gif"
using (FileStream fs2 = new FileStream(saveImgFile, FileMode.Create))
{
gEnc.Save(fs2);
}
I should have mentioned that getting gif frames from this post.
You can do this by using the Graphics object in C#. You can get a Graphics object from the picture ( image.CreateGraphics() - or something like this as I remember ) and the use some of the built in methods for adding text to it like : Graphycs.DrawString() or other related methods.