将UIImage转换为字节数组

我需要将UIImage转换为字节数组。 我正在使用Xamarin的Visual Studio插件来生成iOS应用程序。

下面的代码位获取图像,但我需要将其作为字节数组而不是UIImage发送到服务堆栈。

var signatureView = new SignaturePad.SignaturePadView(new RectangleF(10, 660, 300, 150)); signatureView.BackgroundColor = UIColor.White; this.View.AddSubview(signatureView); UIImage signatureImage = signatureView.GetImage(); 

从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)); } 

自从我检查ServiceStack API以来已经很长时间了,但是如果可能的话 ,尽量避免使用byte[]因为它需要创建相同数据的另一个副本。 在许多情况下并不重要,但图像往往很大。

例如,如果有一个接受System.IO.Stream的重载,那么使用image.AsPNG ().AsStream ()并避免开销:-)

 Stream pst = img.AsPNG().AsStream();