Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UIImage to Byte Array

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();
like image 600
Yahiko Kikikoto Avatar asked Jun 14 '13 15:06

Yahiko Kikikoto


2 Answers

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));
}
like image 83
Jason Avatar answered Oct 07 '22 09:10

Jason


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 :-)

like image 31
poupou Avatar answered Oct 07 '22 08:10

poupou