Ask the Expert

Save/load to XML while preserving a an animated GIF's file properties

Relating to your topic "Can we store an image in XML file, just like we store an image file as binary in SqlDatabase?": I noticed that if this is extended to use GIF images, reloading the image from the XML will cause an animated, transparent GIF to become static and opaque. Is there a way to save/load to XML while preserving all file properties? Thanks.
The code shown in that answer used the Bitmap class. To make the code more generic and correctly handle animated gifs, the image saving code should be modified as follows:
string data = null;
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("NMatrix.gif"));
using (MemoryStream mem = new MemoryStream())
{
  // Could determine image format based on file extension, for example.
  ImageFormat fmt = ImageFormat.Gif;
  img.Save(mem, fmt);
  data = Convert.ToBase64String(mem.ToArray());
}

And reloading:

using (MemoryStream mem = new MemoryStream(Convert.FromBase64String(data)))
{
  //Load the image from the stream, if we needed the Image object
  System.Drawing.Image img = System.Drawing.Image.FromStream(mem);
  //Dump to response.
  Response.BinaryWrite(mem.ToArray());
}

Note that instead of loading a Bitmap object, we're dealing with the generic Image class (not to be confused with the System.Web.UI.WebControls.Image).

This was first published in January 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: