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

9
我在尝试将png图像存储到Windows 8应用的SQLite数据库中,我发现可以通过将其转换为base64字符串并将字符串存储到数据库中来完成此操作。稍后在应用程序中,我希望将该base64字符串转换为png图像,并将其存储到指定位置。问题是我不知道如何在C# Windows 8应用程序中将图像转换为base64和base64转换为图像,并将其存储到指定位置。任何帮助将不胜感激。
1个回答

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

@HardLuck...看起来不错。在第二种方法中,应该在using块中初始化MemoryStream以确保它被正确地处理吗? - Paul
@hardluck 如何将图像存储到应用程序中指定的位置,例如应用程序的资源文件夹? - Justice
如果图像是静态的,请考虑使用资源或解决方案中的文件夹,否则应该在数据库中。如果您需要将其写入文件系统,则只需使用:`Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");// 将图像保存为 GIF。 bmp1.Save("c:\button.gif", System.Drawing.Imaging.ImageFormat.Gif);` - HardLuck
@HardLuck,我尝试了上面的代码,但不幸的是,Windows 8商店应用程序不支持System.drawing dll,因此与该dll相关的任何功能也不受支持。 - Justice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接