Return Bitmap to Browser dynamically

眉间皱痕 提交于 2020-01-24 08:45:05

问题


I am cropping an image, and wish to return it using a ashx handler. The crop code is as follows:

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

The bitmap is being returned, and now need to send that back to the browser through the context stream, as I do not want a physical file created.


回答1:


You really just need to send it over the response with an appropriate MIME type:

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

  }
}

You can change the format to a number of different things; just check the enum.




回答2:


A better approach will be to use write a Handler to accomplish the function. Here is one tutorial that returns image from query string and here is a MSDN article on the topic.




回答3:


Write the bitmap on your response stream (and set the correct mime type)

Might be an idea to convert it to png/jpg to reduce it's sice too



来源:https://stackoverflow.com/questions/1031103/return-bitmap-to-browser-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!