Image Saving

Code:
// create image to draw to
Bitmap ImageToDrawTo=new Bitmap(_width, _height);
// create a graphics object to draw to that image
using(Graphics g = Graphics.FromImage(ImageToDrawTo))
{
//draw
}
// save the image to a file
ImageToDrawTo.Save(@"c:\My Documents\My Pictures\Image.jpg", ImageFormat.Jpeg);
 
Not working

Below is a copy of the code I am using, I can repaint the image to make it smaller that the original but I cant save. Please help?

Dim g As Graphics
Dim myimage As New Bitmap(320, 240)
myimage = Drawing.Image.FromFile("c:\picture\temp.jpg")
g = e.Graphics
g.FromImage(myimage)
g.DrawImage(myimage, 8, 8, 320, 240)
myimage.Save("c:\picture\temp1.jpg")

The language I am using is visual basic.NET.
 
Its not working but its not hard to fix :).
First of all, you are wasting time by creating a new blank bitmap, and then creating a new one again from the file. Load it directly from the file.
Code:
 Dim myimage As New Bitmap("file path")
Im assuming you are doing this in the paint event of an object (form, picbox etc.) since you are using e.Graphics. Well, to draw to your newly created bitmap you dont need that graphics object. You were going in the right direction with this line:
Code:
          g.FromImage(myimage)
But that is not excatly what you need. The FromImage returns a graphics object, it doesnt make replace the object you call it from since it is a shared/static method. And since its shared you can also call it using the class name: Graphics.FromImage. This is how you can get the Graphics object for your bitmap:
Code:
 Dim g As Graphics = Graphics.FromImage(myimage)
Now you can draw onto the bitmap you just created and later save it.
 
Still need help

Thanks for the help. My code is as follows:

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

Dim myimage As New Bitmap("c:\picture\test.jpg")
Dim g As Graphics = g.FromImage(myimage)
g = e.Graphics
g.DrawImage(myimage, 8, 8, 320, 240)
myimage.Save("c:\picture\temp1.jpg")

End Sub

The image test.jpg is 480 x 360. I am trying to resize the picture to 320 x 240. I was able to copy the picture but it was not resized. Please help. Any help given is greatly appreiciated.
 
Example

mutant said:
If you want to resize the picture then use the GetThumbnailImage method of the bitmap object.


Could you give me code sample of how to correctly use the GetThumbnailImage? You help is greatly appreciated.
 
Ah, using DrawImage is better here is how you can do it.
Code:
 create a new bitmap that you will put the scaled version of original on
 Dim newimg As New Bitmap(320, 240) pic the size you want
 Dim gr As Graphics = Graphics.FromImage(newimg) get the graphics for it
 now load the original and draw it onto the new bitmap
 gr.DrawImage(New Bitmap("path to the original picture file"), 0, 0, 320, 240)
 newimg.Save("new file name")
 gr.Dispose() never forget this step :)
 
Back
Top