2009-06-23 30 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文章。

相關問題