Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Image Serializing

Tags:

c#

image

wcf

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.

like image 965
John Isaiah Carmona Avatar asked Jan 26 '12 06:01

John Isaiah Carmona


1 Answers

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();
}
like image 112
Marc Gravell Avatar answered Sep 21 '22 21:09

Marc Gravell