简体   繁体   English

如何将图像(.png)转换为base64字符串,反之亦然,并将其转换为指定位置

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

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. 我正在尝试将图像(png)存储到Windows 8应用程序中的sqlite数据库,我发现它可以通过将其转换为base64字符串并将字符串存储到数据库来完成。 Later on in the app i want to convert that base64 string to png image and store it to a specified location. 稍后在应用程序中我想将该base64字符串转换为png图像并将其存储到指定位置。 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. 问题是我不知道如何将图像转换为base64和base64图像并将其存储到c#windows 8 app中的指定位置。 Any help would be appreciated. 任何帮助,将不胜感激。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM