2009-06-23 55 views
3

我正在裁剪图像,并希望使用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; 
     } 
    } 

位图被返回,而现在需要发送通过上下文流,其返回给浏览器,因为我不希望创建一个物理文件。

回答

9

你真的只需要使用适当的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); 

    } 
} 

您可以更改格式的一些不同的东西;只需检查枚举。

1

写上您的响应流的位图(和设置正确的MIME类型)

可能是一个想法,将它转换成PNG/JPG格式,以减少它的SICE太

2

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