Ever wanted to convert an Android Bitmap Image to dot net byte array ? or how about converting iOS UIImage to dot net byte array ? Ever wondered how to implement either ?😉 Well then you are about to find out how!
Alright so there was this one time…
I wanted to create a Custom Image Loader service using Dependency Service in Xamarin Forms.
It’s suppose to be easy, but the only problem was getting the different Image types in Android and iOS to a common data type!??%$@##!!😦
Byte array for the Rescue
So just like you would have assumed by now, I wanted to convert the both Android and iOS Image types to dot net byte array type so that I could use them in my PCL library for the Xamarin Forms project. More specifically converting Android Bitmap Image to byte array and iOS UIImage to byte array was my specific requirement.
Well, as usual here I am sharing the code implementation, incase if any of you are going through the same situation, here’s how I implemented it.😉
Android Bitmap Image to byte array ?
It’s pretty straightforward, We create a Memory Stream and compress the Bitmap image into it as follows.
There you go, from the Memory Stream you extract the byte array.
iOS UIImage Image to byte array ?
In iOS first we create a blank byte array with the length sufficient to hold our Image’s size. We are going to use Marshal.Copy() method to copy our UIImage’s NSData.Bytes to our byte array as follows.
Now pass around the myByteArray, wherever you want. lol
There you have it folks!😀