将 base 64 字符串转换为图像并保存 [英] converting a base 64 string to an image and saving it
问题描述
这是我的代码:
protected void SaveMyImage_Click(object sender, EventArgs e)
{
string imageUrl = Hidden1.Value;
string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png") ;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
顶部的 imageUrl 声明正在接收 Base64 图像字符串,我想将其转换为图像.我认为我的代码集仅适用于www.mysite.com/test.jpg"之类的图像,不适用于 Base64 字符串.有人有什么建议吗?谢谢!
The top imageUrl declartion is taking in a Base64 image string, and I want to convert it into an image. I think my set of code only works for images like "www.mysite.com/test.jpg" not for a Base64 string. Anybody have some suggestions? Thanks!
推荐答案
这里是一个例子,你可以修改方法来接受一个字符串参数.然后只需使用 image.Save(...) 保存图像对象.
Here is an example, you can modify the method to accept a string parameter. Then just save the image object with image.Save(...).
public Image LoadImage()
{
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
当字节表示位图时,可能会出现异常GDI+ 中发生一般错误.
.如果发生这种情况,请在处理内存流之前保存图像(仍然在 using 语句中).
It is possible to get an exception A generic error occurred in GDI+.
when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).
这篇关于将 base 64 字符串转换为图像并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!