这是我的代码:
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字符串。有人有建议吗?谢谢!
这是一个示例,您可以修改该方法以接受字符串参数。然后只需使用 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; }
A generic error occurred in GDI+.当字节代表位图时,可能会发生异常。如果发生这种情况,请在处理内存流之前保存映像(同时仍在using语句中)。
A generic error occurred in GDI+.