[.net] Saving an image to a file...

Started by
4 comments, last by barakus 19 years, 2 months ago
I was wondering, how can you save an image into another file? I need this for my map editor because at the moment you need the images in the same folder as the map file but it would be much better if the images needed were saved within the file. [Edited by - barakus on January 16, 2005 4:35:35 PM]
Advertisement
I'm not sure I understand you completely. Immediately before you want to save it, where is the image?
- k2"Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ} | {Blog/Journal} | {[email=kkaitan at gmail dot com]e-mail me[/email]} | {excellent webhosting}
Assuming you already have a System.Drawing.Image object...

FileStream myFile = new FileStream("myMapFile.map", FileMode.Create);//...write some of your map data to the file//Save with whatever format you choose; bmp, jpg, png, gif, etc.myImage.Save(myFile, System.Drawing.Imaging.ImageFormat.Bmp);//...write the rest of the data to your filemyFile.Close();
Thanks thats just what i needed. Just one problem now,how do i read the image ?
Should i just store the size of the image in bytes and read it with the binary reader?
If so how do i find the size of the image in bytes?
EDIT: The image is stored in a Bitmap but it can be a either a png,bmp, or a tga
Storing a lot of different stuff in one file can be a real pain. To use the Image.FromStream/FromFile methods you will have to read the exact number of bytes into either a memorystream or a temp file and then use the right method to load it (be sure to read the docs on these methods -- FromStream requires you to keep the stream open so long as you are using the image). This means that you will have to write the size the image to the file as well or use some sort of delimiter/endoding method. The final size of the image depends on what codec you use to save it (see ImageCodecInfo). With many codecs you will not know the size of the image until after you are done writing it. Try looking at the stream's Position before and after the write (of course that makes it hard to write the size before the image).

My advice: Use something like SharpZipLib to manage your file (and get the benifits of compression) or some other library, it is probably worth the research.

Also look into serialization for other types of data, it is generally a very effective way of packing things up but it does have some pitfalls.
thanks i'll look into it.

This topic is closed to new replies.

Advertisement