18

I need to convert a UIImage to a byte array. I am using Xamarin's Visual Studio plugin to produce an iOS application.

The bit of code below gets the image, but I need to send it across a Service Stack as a byte array instead of a UIImage.

        var signatureView = new SignaturePad.SignaturePadView(new RectangleF(10, 660, 300, 150));
        signatureView.BackgroundColor = UIColor.White;
        this.View.AddSubview(signatureView);
        UIImage signatureImage = signatureView.GetImage();
Yahiko Kikikoto
  • 688
  • 3
  • 12
  • 23

3 Answers3

32

Shamelessly stolen from ChrisNTR

using (NSData imageData = image.AsPNG()) {
  Byte[] myByteArray = new Byte[imageData.Length];
  System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
}
Jason
  • 86,222
  • 15
  • 131
  • 146
17

It's been a long time since I checked the ServiceStack API but, if possible, try to avoid byte[] since it will need to create another copy of the same data. It does not matter in many cases but images are often huge.

E.g. if there's an overload that accept a System.IO.Stream then use image.AsPNG ().AsStream () and avoid the overhead :-)

poupou
  • 43,413
  • 6
  • 77
  • 174
  • 4
    Using image.AsPNG() does not keep the orientation flag, so it seems better to use image.AsJPEG() to get the stream. That took me two hours ;-). – asp_net Feb 24 '14 at 16:36
14
Stream pst =   img.AsPNG().AsStream();
Hâluk Yilmaz
  • 237
  • 5
  • 12