如何将图像 (.png) 转换为 base64 字符串,反之亦然并将其存储到指定位置 [英] How to Convert image (.png) to base64 string, vice a versa and strore it to a specified location

查看:33
本文介绍了如何将图像 (.png) 转换为 base64 字符串,反之亦然并将其存储到指定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像 (png) 存储到 Windows 8 应用程序中的 sqlite 数据库,我发现可以通过将其转换为 base64 字符串并将该字符串存储到数据库来完成.稍后在应用程序中,我想将该 base64 字符串转换为 png 图像并将其存储到指定位置.问题是我不知道如何将图像转换为 base64 并将 base64 转换为图像并将其存储到 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.

推荐答案

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

这篇关于如何将图像 (.png) 转换为 base64 字符串,反之亦然并将其存储到指定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆