动态返回位图给浏览器

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;
        }
    }

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

3个回答

11

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

  }
}

你可以将格式更改为许多不同的东西;只需检查枚举即可。


3
更好的方法是使用Handler来完成该功能。这里有一个教程,可以从查询字符串返回图像,这是一个MSDN文章的链接。请参照此处此处的内容。

1

将位图写入响应流中(并设置正确的MIME类型)

将其转换为png / jpg以减小尺寸可能是个好主意。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接