- C# code
Stream stream = null; StreamReader reader = null; MemoryStream ms = null; HttpWebResponse webResponse = null; try { WebRequest webRequest = HttpWebRequest.Create("http://image.sjq.cn/img/201002/99913/1213.jpg"); //打开图片地址 webResponse = (HttpWebResponse)webRequest.GetResponse(); stream = webResponse.GetResponseStream(); reader = new StreamReader(stream); string textContent = reader.ReadToEnd(); byte[] bytes = System.Text.Encoding.Default.GetBytes(textContent); ms = new MemoryStream(bytes); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); [color=#FF0000] ms参数无效[/color] //记录是否是图片个格式 bool imgState = false; if (img.RawFormat == ImageFormat.Gif) imgState = true; if (img.RawFormat == ImageFormat.Jpeg) imgState = true; if (img.RawFormat == ImageFormat.Png) imgState = true; if (imgState) { imgHeight = img.Height; imgWidth = img.Width; imgSize = int.Parse(img.Size.ToString()); md5 = getMd5Hash(textContent); if (ImagesManager.GetImgMarkIsExits(md5)) { message = "该图片已经存在!"; return false; } return true; } else { message = "该URL地址的目标不是图片"; return false; } } catch (Exception ex) { message = ex.Message; message = "图片上传操作异常"; return false; } finally { webResponse.Close(); stream.Dispose(); stream.Close(); reader.Dispose(); reader.Close(); ms.Dispose(); ms.Close(); }
byte[] bytes = System.Text.Encoding.Default.GetBytes(textContent);
ms = new MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
报错:ms参数无效。
不知道什么原因
我之前用FileUpload上传的图片也是用这段代码就没问题。
------解决方案--------------------------------------------------------
废话啊
你获取过来的就是字节数组 干嘛要转换为文字?
stream = webResponse.GetResponseStream();
MemoryStream ms = new MemoryStream(stream );
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
------解决方案--------------------------------------------------------
新建的web技术交流群,欢迎大家加入一起讨论:
群号:29037453
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
stream = webResponse.GetResponseStream();
reader = new StreamReader(stream);
[color=#FF0000] string textContent = reader.ReadToEnd();[/color
这里数据就错误了。 你不能把byte[]直接转换为字符串
直接修改成
byte[] bytes = new System.Net.WebClient().DownloadData(“http://image.sjq.cn/img/201002/99913/1213.jpg”);
------解决方案--------------------------------------------------------
up回复内容太短了!