Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert image (.png) to base64 string, vice a versa and strore it to a specified location

Tags:

c#

windows-8

I'm trying to store images (png) to sqlite database in a windows 8 app, and i figured out it can be done by converting it to base64 string and storing the string to the database. Later on in the app i want to convert that base64 string to png image and store it to a specified location. The Problem is i don't know how to convert images to base64 and base64 to image and store it to a specified location in c# windows 8 app. Any help would be appreciated.

like image 223
Justice Avatar asked Feb 26 '13 12:02

Justice


People also ask

How do I store images in Base64?

Play with image base64 encode Just upload your image from a local computer or give the tool a URL to an image file on the internet then the tool will give you a base64 encoded string. In addition, the tool also provides you appropriate data URI, code snippet to embed your image into a HTML file as well as a CSS file.

Can we convert image to Base64?

The Image encoding tool supports loading the Image File to transform to Base64. Click on the Upload Image button and select File. Image to Base64 Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

Can a PNG be Base64?

To convert PNG to base64 data: Click on "Choose file" and upload the PNG image from your system. Click on the "Convert" button to convert the PNG image into base 64 data. You can "Download or Copy" the base 64 code for further use.


1 Answers

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
    return Convert.ToBase64String(imageBytes);
  }
}

public Image Base64ToImage(string base64String)
{
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        return Image.FromStream(ms, true);
    }
}
like image 168
HardLuck Avatar answered Oct 25 '22 17:10

HardLuck