iOS Xamarin - Pushing / Retrieving - UIImage To 64 Base String Using Azure Mobile Service

A fine day at desk started working on iOS Xamarin. I had to push image to Azure Mobile Service Database and then had to retrieve that. As per requirement I had to use string to save image and retrieve. The only option found was by converting image to array of bytes and then converting that to base 64 String and save that image to database.

In iOS we have UIImage and UIImageView, here UIImage is the image with source whereas UIImageView is the control that we use to display image. If I relate that with Windows Phone it's like Image Control and Image Source. Similarly it's UIImageView.Image that has UIImage as:

{ get; set; }

There are many ways to convert image to byte[] array and then convert byte[] array to Base64 String, but unfortunately when decoding that image string, UIImage always returned to be "null" and I wasn't able to generate image from string. I tried finding different solution of different forums but no forum had answer to that. If they has a solution for encoding and decoding that turned to be returning "null" at the end.

So what's the solution? Well here it is,

Encoding

  1. string encodedString = img_imageView.Image.AsJPEG (0.23f).GetBase64EncodedString (NSDataBase64EncodingOptions.None);  
Here, 0.23f is compression quality of image. Here you can directly save this string to database.

Decoding

Decoding was something I found no solution for end and ended up in frustration for some time.
  1. byte[] encodedDataAsBytes = System.Convert.FromBase64String (ImageStringToDecode);  
  2. NSData ImageData = NSData.FromArray(encodedDataAsBytes);  
  3. var img = UIImage.LoadFromData(Imagedata);  
  4. img_toView.Image = img;  
These lines of code would always return you image and that would be displayed on your screen.

Here are few screeshots of the code,

get image

push

Note: Due to NDA I can't share the code.

I hope this article has saved you from frustration.
Happy coding!

 


Similar Articles