John Isaiah Carmona
John Isaiah Carmona

Reputation: 5356

WCF Image Serializing

I have this code in my WCF Service:

public class MyImage
{
    public Image Image { get; set; }
    public string FullPath { get; set; }
}

[ServiceContract]
public interface IMyService
{
    [OperationContract] void SaveImage(MyImage myImg);
}

public class MyService : IMyService
{
    public void SaveImage(MyImage myImg)
    {
        // ...
    }
}

But this error occur when I run the SaveImage() method:

There was an error while trying to serialize parameter http://tempuri.org/:e. The InnerException message was 'Type 'System.Drawing.Bitmap' with data contract name 'Bitmap:http://schemas.datacontract.org/2004/07/System.Drawing' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'

My code is in C#, Framework 4.0, build in Visual Studio 2010 Pro.

Please help, thanks in advance.

Upvotes: 5

Views: 7401

Answers (2)

Emond
Emond

Reputation: 50672

As you can read here: Need serialize bitmap image silverlight an Image is not serializable. So you could turn the image into a byte array (of any format you like, ranging from just pixel colors to an official format such as PNG) and use that

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062755

The data-contract expected Image, but it got a Bitmap : Image instance. WCF likes to know about inheritance in advance, so you would need to tell it. But! I honestly don't think that is a good approach; you should really just throw the raw binary around instead - which probably means saving the Image to a MemoryStream first. You should also formally decorate your contract type. I would be sending:

[DataContract]
public class MyImage
{
    [DataMember]
    public byte[] Image { get; set; }
    [DataMember]
    public string FullPath { get; set; }
}

An example of getting the byte[]:

using(var ms = new MemoryStream()) {
    image.Save(ms, ImageFormat.Bmp);
    return ms.ToArray();
}

Upvotes: 15

Related Questions