使用WebClient获取远程图片会产生颗粒状GIF,无法处理PNG+BMPGreetings!我正在创建一个网络表单原型(ImageLaoder.aspx),它将返回一个图像,以便它可以像其他简单的网络表单/网页示例一样使用:到目前为止,它加载JPG没有问题,但它不匹配原始数据比,GIF看起来“颗粒状”,而BMP和PNG导致以下异常:e){stringl_filePath=Request.QueryString["i"];System.Drawing.Imagel_image=GetImage(l_filePath);如果(l_image!=null){System.Drawing.Imaging.ImageFormatl_imageFormat=DetermineImageFormat(l_filePath);WriteImageAsReponse(l_image,l_imageFormat);}}privateSystem.Drawing.ImageGetImage(stringfilePath){WebClientl_WebClient=newWebClient();byte[]l_imageBytes=l_WebClient.DownloadData(filePath);System.Drawing.Imagel_image=null;使用(MemoryStreaml_MemStream=newMemoryStream(l_imageBytes,0,l_imageBytes.Length)){l_MemStream.Write(l_imageBytes,0,l_imageBytes.Leng);l_image=System.Drawing.Image.FromStream(l_MemStream,true);l_MemStream.Close();}返回l_image;}privateSystem.Drawing.Imaging.ImageFormatDetermineImageFormat(stringfilePath){if(filePath.EndsWith(".jpg",StringComparison.OrdinalIgnoreCase))returnSystem.Drawing.Imaging.ImageFormat.Jpeg;elseif(filePath.EndsWith(".gif",StringComparison.OrdinalIgnoreCase))返回System.Drawing.Imaging.ImageFormat.Gif;elseif(filePath.EndsWith(".png",StringComparison.OrdinalIgnoreCase))返回System.Drawing.Imaging.ImageFormat.Png;否则返回System.Drawing.Imaging.ImageFormat.Bmp;}privatevoidWriteImageAsReponse(System.Drawing.Imageimage,System.Drawing.Imaging.ImageFormatimageFormat){if(image==null)return;System.Drawing.Bitmapl_outputBitMap=newBitmap(image);如果(imageFormat==System.Drawing.Imaging.ImageFormat.Jpeg)Response.ContentType="image/jpg";elseif(imageFormat==System.Drawing.Imaging.ImageFormat.Gif)响应onse.ContentType="图片/gif";elseif(imageFormat==System.Drawing.Imaging.ImageFormat.Png)Response.ContentType="image/png";elseResponse.ContentType="图像/bmp";l_outputBitMap.Save(Response.OutputStream,imageFormat);知道为什么GIF是颗粒状的,PNG和BMP导致异常吗?关于GetImage方法的几点:简而言之,我相信您的GetImage方法可以替换为:privateImageGetImage(stringfilePath){WebClientl_WebClient=newWebClient();byte[]l_imageBytes=l_WebClient.DownloadData(filePath);MemoryStreaml_stream=newMemoryStream(l_imageBytes);返回Image.FromStream(l_stream);现在,更重要的是——你为什么要加载图像?为什么不直接将文件本身作为响应,像您已经在做的那样设置内容类型——或者可能只是基于扩展名?换句话说,您的所有代码都将变为:protectedvoidPage_Load(objectsender,EventArgse){stringfilePath=Request.QueryString["i"];字符串扩展名=l_filePath.Substring(l_filePath.LastIndexOf('.')+1);Response.ContentType="图片/"+扩展名;byte[]data=newWebClient.DownloadData(filePath);Response.OutputStream.Write(数据,0,data.长度);响应.End();更多的错误处理(包括“这是一个合理的扩展吗?”)会很好,但除此之外我认为这并不重要。实际加载图像的唯一好处是,您可以验证它确实是图像而不是病毒或类似的东西。编辑:出于兴趣,您是否有充分的理由希望图像请求通过您的服务器?为什么网络作者会写:相反,它可能有用的原因有几个,但在许多情况下,这只是一种浪费。以上是C#学习教程:使用WebClient获取远程图片会产生颗粒状的GIF,无法处理所有PNG+BMP共享的内容。如果对大家有用,需要了解更多C#学习教程,希望大家多加关注——本文来自网络收藏,不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
