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

标签 c# windows-8

我正在尝试将图像 (png) 存储到 Windows 8 应用程序中的 sqlite 数据库,我发现可以通过将其转换为 base64 字符串并将该字符串存储到数据库来完成。稍后在应用程序中我想将该 base64 字符串转换为 png 图像并将其存储到指定位置。问题是我不知道如何将图像转换为 base64 并将 base64 转换为图像并将其存储到 c# windows 8 应用程序中的指定位置。任何帮助将不胜感激。

最佳答案

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

关于c# - 如何将图像(.png)转换为base64字符串,反之亦然,并将其存储到指定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15089359/

相关文章:

c# - Windows 8 中的动态磁贴是如何制作的?

c# - 使用 Caliburn.Micro 设置窗口标题

c# - 为什么这是错误的? (C# 任务继续)

c# - WPF Datagrid - 订阅单元格加载事件?

c# - 父面板点击事件

windows-8 - Windows Notification Server 上的附加参数

c# - 等待 CancellationToken 取消请求

windows-8 - 在 Win8 和 WP8 应用程序中共享静态库

windows-8 - VirtualBox 严重错误 - Windows 8

c# - 您应该在 Windows 8 应用程序的哪个位置编码 'privacy policy' ?