【问题标题】:How to Convert image (.png) to base64 string, vice a versa and strore it to a specified location如何将图像 (.png) 转换为 base64 字符串,反之亦然并将其存储到指定位置
【发布时间】:2019-08-12 08:16:27
【问题描述】:

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

【问题讨论】:

    标签: c# windows-8


    【解决方案1】:
    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 以确保正确处理它吗?
    • @hardluck 如何将图像存储到应用程序中的指定位置说应用程序的资产文件夹?
    • 如果图像是静态的,请考虑在解决方案中使用资源或文件夹,否则它应该在数据库中。如果您需要将其写入文件系统而不仅仅是使用:Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp"); // Save the image as a GIF. bmp1.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Gif);
    • @HardLuck 我尝试了上面的代码,但遗憾的是 Windows 8 商店应用程序不支持 System.drawing dll,因此也不支持任何相关的功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2011-05-27
    • 2017-05-22
    相关资源
    最近更新 更多