Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Base64 String to Bitmap or Image Xamarin or Android [duplicate]

I'm trying to convert a Base64 string to an image and set ImageView using the same image. I know how to get it done in java, but I'm having a trouble in C#. Anyone have an idea of how to get it done in C#?

Some of the code I've tried;

public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }
like image 811
Joewy Lombe Avatar asked May 02 '16 01:05

Joewy Lombe


3 Answers

Base64 to Bitmap :

public Bitmap Base64ToBitmap(String base64String)
{
    byte[] imageAsBytes = Base64.Decode(base64String, Base64Flags.Default);
    return BitmapFactory.DecodeByteArray(imageAsBytes, 0, imageAsBytes.Length);
}

Bitmap to Base64 :

public String BitmapToBase64(Bitmap bitmap)
{
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.ToByteArray();
    return Base64.EncodeToString(byteArray, Base64Flags.Default);
}
like image 197
Yksh Avatar answered Oct 17 '22 12:10

Yksh


Image to Base64 String, online conversion - here

 public string ImageToBase64(Image image, 
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Base64 String to Image, online conversion - here

    public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0, 
    imageBytes.Length);

  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}
like image 41
Vishwesh Jainkuniya Avatar answered Oct 17 '22 12:10

Vishwesh Jainkuniya


I'm assuming that your encoded data is some bitmap format? If so, you should be able to do something like this:

public Bitmap Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Bitmap image = BitmapFactory.FromStream(ms, true);
        return image;
    }
 }
like image 3
Jason Avatar answered Oct 17 '22 11:10

Jason