Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding on Image but I need a byteArray

I'm working with Winforms, CAB, C# and Infragistics. I'm trying to work with MVP with my backend connected with WCF.

In my presenter I've my Model, let's call it AgreementDataContract. This data contract has a bunch of attributes:

    ...
    [DataMember]
    public byte[] PVImage { get; set; }

    [DataMember]
    public byte[] OntwerpImage { get; set; }

    [DataMember]
    public Decimal WattpiekPrijs { get; set; }
    ...

You'll notice that the Image is stored as a byte[]. I bind these attributes to the controls on my user control:

    BindingHelper.BindField(_ultraPictureBoxPV, "Image", _bindingSource, "PVImage");
    BindingHelper.BindField(_ultraPictureBoxOntwerp, "Image", _bindingSource, "OntwerpImage");

BindingHelper just adds a BindingContext to the specified Controler (control.BindingContext.Add(...)).

Anyways, the problem: the data contract contains the image as a bytearray, whilest I'm binding to an Image. This causes the attribute to remain "null", because he doesn't feel like putting an Image in a byteArray ;)

I've tried playing around with it, but I think I've 2 possibilities:

  1. I can try to use a sort of converter? So when an Image is inserted it's passed along as a byteArray instead of an Image to the Model (=databinding).

  2. I can drop the binding and make an event when the form is "submitted" and convert the image to byteArray myself and fill up the model. (=no databinding)

TL;DR; Do you know of a way to "convert" an image to a bytearray when it's being passed to the databinding?

I hope my question is clear! Thanks for the help

like image 525
Team-JoKi Avatar asked Sep 13 '11 13:09

Team-JoKi


1 Answers

I would add a new property of type Image which will be bindable to your UltraPictureBox control. Add two methods that know how to convert in either direction.

[DataMember]
public Image OntwerpImageImage
{
    get { return ConvertByteArrayToImage(OntwerpImage); }
    set { OntwerpImage = ConvertImageToByteArray(value); }
}

//[DataMember]
public byte[] OntwerpImage { get; set; }

public Image ConvertByteArrayToImage(Byte[] bytes)
{
    var memoryStream = new MemoryStream(bytes);
    var returnImage = Image.FromStream(memoryStream);
    return returnImage;
}

public Byte[] ConvertImageToByteArray(Image image)
{
    var memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);
    return memoryStream.ToArray();
}
like image 86
Tim Smojver Avatar answered Sep 28 '22 05:09

Tim Smojver