Thomas Wingfield
Thomas Wingfield

Reputation: 95

Need serialize bitmap image silverlight

I need serialize custom class with bitmapImage(tagged by xmlIgnore right now). I'm using xmlSerialization, but I think thats bad.Do you have some ideas how can I serialize my class??Probably you can provide some simple example??

class X
{
private BitmapImage someImage;
public BitmaImage{get;set}
}

Actually later I will be use WCF Service. Thanks)

Upvotes: 2

Views: 1292

Answers (2)

brunnerh
brunnerh

Reputation: 184486

You can expose the image as a byte array, e.g.:

public byte[] ImageAsBytes
{
    get { return BytesFromImage(someImage); }
    set { someImage = ImageFromBytes(value); }
}

You can of course convert back using a stream and the StreamSource property.

Upvotes: 2

keyboardP
keyboardP

Reputation: 69372

You could convert the image to a Base64 string. Examples from here:

//Convert image to the string
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
   using (MemoryStream ms = new MemoryStream())
   {
     // Convert Image to byte[]
     image.Save(ms, format);
     byte[] imageBytes = ms.ToArray();

     // Convert byte[] to Base64 String
     string base64String = Convert.ToBase64String(imageBytes);
     return base64String;
   }
}

//when deserializing, convert the string back to an image
public Image Base64ToImage(string base64String)
{
   // Convert Base64 String to byte[]
   byte[] imageBytes = Convert.FromBase64String(base64String);
   MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);    
   // Convert byte[] to Image
   ms.Write(imageBytes, 0, imageBytes.Length);
   Image image = Image.FromStream(ms, true);
   return image;
}

Upvotes: 2

Related Questions