如何将图像转换为base64

时间:2014-09-25 10:06:13

标签: c# windows-8.1

我想将图像转换为base64,以便使用C#将其存储在Sqlite中,但此代码不适用于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
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

1 个答案:

答案 0 :(得分:0)

我相信您要求Windows Store API解决此问题:

public async Task<string> ImageToBase64(StorageFile MyImageFile)
    {
        Stream ms = await MyImageFile.OpenStreamForReadAsync();
        byte[] imageBytes = new byte[(int)ms.Length];
        ms.Read(imageBytes, 0, (int)ms.Length);
        return Convert.ToBase64String(imageBytes);
    }