简体   繁体   English

将UIImage转换为字节数组

[英]Converting UIImage to Byte Array

I need to convert a UIImage to a byte array. 我需要将UIImage转换为字节数组。 I am using Xamarin's Visual Studio plugin to produce an iOS application. 我正在使用Xamarin的Visual Studio插件来生成iOS应用程序。

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. 下面的代码部分获取了图像,但是我需要将其作为字节数组而不是UIImage跨服务堆栈发送。

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

Shamelessly stolen from ChrisNTR 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));
}

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. 自从我检查ServiceStack API已经很长时间了,但是, 如果可能的话 ,请尽量避免使用byte[]因为它将需要创建相同数据的另一个副本。 It does not matter in many cases but images are often huge. 在许多情况下都没有关系,但是图像通常很大。

Eg if there's an overload that accept a System.IO.Stream then use image.AsPNG ().AsStream () and avoid the overhead :-) 例如,如果有接受System.IO.Stream的重载,则使用image.AsPNG ().AsStream ()并避免开销:-)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM