Xamarin.iOSでUIImage型のバッファとbyte型とを相互に変換してみましょう。
UIImage型とbyte型とでは相互に直接型の変換をおこなうことができません。一度、NSData型に変換した上で希望する型への変換をおこないます。
UIImageとbyteとを相互に変換する
UIImage → byte
public byte[] UiimageToByteArray(UIImage image) { byte[] bytes = null; try { using (var data = image.AsPNG()) { bytes = data.ToArray(); } } catch (Exception) { bytes = null; } return bytes; }
byte[] → UIImage
public UIImage ByteArrayToUiimage(byte[] bytes) { UIImage image = null; try { image = new UIImage(NSData.FromArray(bytes)); } catch (Exception ex) { image = null; } return image; }
拡張メソッドクラス化したもの
上記のメソッドを拡張メソッドクラスにしてみました。
using System; using Foundation; using UIKit; namespace Softbuild.Media { public static class UIImageConvertExntensions { public static byte[] ToBytes(this UIImage image) { byte[] bytes = null; try { using (var data = image.AsPNG()) { bytes = data.ToArray(); } } catch (Exception) { bytes = null; } return bytes; } public static UIImage FromBytes(byte[] bytes) { UIImage image = null; try { image = new UIImage(NSData.FromArray(bytes)); } catch (Exception) { image = null; } return image; } } }
関連記事
Xamarin.iOSを使ってアプリ開発する際に逆引きとしてお使いください。