【问题标题】:Return Bitmap to Browser dynamically动态返回位图到浏览器
【发布时间】:2009-06-23 07:31:42
【问题描述】:

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

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

【问题讨论】:

    标签: c# asp.net image-manipulation ashx


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        将它转换为 png/jpg 以减少它的大小可能是一个想法

        【讨论】:

          猜你喜欢
          • 2013-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-24
          • 1970-01-01
          • 2015-03-15
          • 2016-05-30
          • 2011-12-25
          相关资源
          最近更新 更多