简体   繁体   English

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

[英]converting base64 to image and showing in gridview

i'm working on a website that takes its data from a web service. 我正在使用从Web服务获取其数据的网站。 Our Android developer gave me a Base64 string like this. 我们的Android开发人员给了我这样的Base64字符串。

iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAYAAAB1ovlvAAAABHNCSVQICAgIf. iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAYAAAB1ovlvAAAABHNCSVQICAgIf。 . . . . . . . . .

I'm saving this string to my database. 我将此字符串保存到数据库中。 I would like to know how I can convert this to an image. 我想知道如何将其转换为图像。

Here is the solution for you 这是给您的解决方案

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

If you're showing it in a web page (You added asp.net as one of your tags so I'm assuming this is for the web) you can cheat and do this: 如果要在网页中显示它(您将asp.net添加为标签之一,所以我假设这是针对Web的),则可以作弊并执行以下操作:

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

This assumes that the image is a png, otherwise change it to image/jpg or whatever. 这假定图像是png,否则将其更改为image / jpg或其他。

The downside is this stops the image being cached. 缺点是这会停止图像的缓存。 So in practice the solution by @Sachin is more practical. 因此,在实践中,@ Sachin的解决方案更为实用。 This way is just neat if you want to avoid saving the files for whatever reason (or just want a 'I need it to work now' solution) 如果您出于某种原因要避免保存文件(或者只希望“我现在需要它才能正常工作”的解决方案),则这种方法非常简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM