5

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.

John Isaiah Carmona
  • 5,260
  • 10
  • 45
  • 79

2 Answers2

15

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();
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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

Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115
  • System.Drawing.Image has a SerializableAttribute so I think it's serializable. See here for reference: http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx – John Isaiah Carmona Jan 26 '12 at 06:31
  • That attribute is not for xml serialization. WCF uses the DataContractSerializer. http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx which uses XML serialization. – Emond Jan 26 '12 at 06:41
  • Ok, I'll just convert it to byte[]. Thanks. – John Isaiah Carmona Jan 26 '12 at 06:51