将base64转换为图像并显示在gridview中

本文关键字:显示 gridview 图像 base64 转换 | 更新日期: 2023-09-27 18:09:42

我在一个网站上工作,从网络服务中获取数据。我们的Android开发者给了我一个Base64字符串,就像这样。

iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAYAAAB1ovlvAAAABHNCSVQICAgIf. . . . . . . . . .

我将这个字符串保存到我的数据库中。我想知道如何将其转换为图像

将base64转换为图像并显示在gridview中

这是你的解决方案

public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0,imageBytes.Length);
  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}

如果你在网页中显示它(你添加了asp.net作为你的标签之一,所以我假设这是为网络),你可以欺骗和这样做:

<img src="data:image/png;base64,<%=base64String%>"/>

这里假设图像为png格式,否则将其更改为image/jpg或其他格式。

缺点是这会停止缓存图像。因此,在实践中,@Sachin的解决方案更实用。如果你想避免保存文件(或者只是想要一个"我需要它现在工作"的解决方案),这种方法很简洁