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

This topic is 4994 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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]

##### Share on other sites
I'm not sure I understand you completely. Immediately before you want to save it, where is the image?

##### Share on other sites
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();

##### Share on other sites
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

##### Share on other sites
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.

##### Share on other sites
thanks i'll look into it.

1. 1
2. 2
Rutin
22
3. 3
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 9
• 11
• ### Forum Statistics

• Total Topics
632567
• Total Posts
3007109

×