动态地将位图返回到浏览器

我正在裁剪图像,并希望使用ashx处理程序返回它。 裁剪代码如下:

public static System.Drawing.Image Crop(string img, int width, int height, int x, int y) { try { System.Drawing.Image image = System.Drawing.Image.FromFile(img); Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb); bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution); Graphics gfx = Graphics.FromImage(bmp); gfx.SmoothingMode = SmoothingMode.AntiAlias; gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; gfx.PixelOffsetMode = PixelOffsetMode.HighQuality; gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel); // Dispose to free up resources image.Dispose(); bmp.Dispose(); gfx.Dispose(); return bmp; } catch (Exception ex) { return null; } } 

正在返回位图,现在需要通过上下文流将其发送回浏览器,因为我不想创建物理文件。

您真的只需要使用适当的MIME类型通过响应发送它:

 using System.Drawing; using System.Drawing.Imaging; public class MyHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { Image img = Crop(...); // this is your crop function // set MIME type context.Response.ContentType = "image/jpeg"; // write to response stream img.Save(context.Response.OutputStream, ImageFormat.Jpeg); } } 

您可以将格式更改为许多不同的内容; 只需检查枚举。

更好的方法是使用write a Handler来完成该function。 这是一个从查询字符串返回图像的教程, 这是关于该主题的MSDN文章。

在响应流上写入位图(并设置正确的mime类型)

可能是一个想法,将其转换为png / jpg,以减少它的sice