0

Here's my situation: I have a console application that creates screenshots of webpages in a bitmap format and then saves it to a database as a byte array.

Then I have a Generic Handler that basically gets the byte array and then returns the image (it is set as the html image source). Here is the code:

public void ProcessRequest(HttpContext context)
{
    int id = Convert.ToInt32(context.Request.QueryString["Id"]);

    context.Response.ContentType = "image/jpeg";
    MemoryStream strm = new MemoryStream(getByteArray(id));
    byte[] buffer = new byte[4096];
    int byteSeq = strm.Read(buffer, 0, 4096);
    while (byteSeq > 0)
    {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = strm.Read(buffer, 0, 4096);
    }
}

public Byte[] getByteArray(int id)
{
    EmailEntities e = new EmailEntities();

    return e.Email.Find(id).Thumbnail;
}

(I did not write that code myself)

The Image although is of course still returned as a bitmap and is far too big in size. Which is why I wanted to return it as a compressed jpg or png, as long as it is small.

So my question to you: What possibilities are there to do this without having to save the image to the filesystem directly?

Thanks in advance for your responses.

4

1 回答 1

1

以下代码段应该让您更接近您的目标。

这假设从数据库中检索到的字节数组可以被 .net 解释为有效图像(例如,简单的位图图像)。

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        int id = Convert.ToInt32(context.Request.QueryString["Id"]);
        var imageBytes = getByteArray(id);
        using (var stream = new MemoryStream(imageBytes))
        using (var image = Image.FromStream(stream))
        {
            var data = GetEncodedImageBytes(image, ImageFormat.Jpeg);

            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(data);
            context.Response.Flush();
        }
    }

    public Byte[] getByteArray(int id)
    {
        EmailEntities e = new EmailEntities();

        return e.Email.Find(id).Thumbnail;
    }

    public byte[] GetEncodedImageBytes(Image image, ImageFormat format)
    {
        using (var stream = new MemoryStream())
        {
            image.Save(stream, format);
            return stream.ToArray();
        }
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

在 web.config 中:

  <system.webServer>
    <handlers>
      <add name="ImageHandler" path="/ImageHandler" verb="GET" type="ImageHandler" preCondition="integratedMode" />
    </handlers>
  </system.webServer>

如果您需要控制压缩/质量,则需要开始查看以下内容:https ://stackoverflow.com/a/1484769/146999

或者你可以选择无损的 PNG——如果大多数图像是图形/UI/文本,它可能会更好地压缩。如果是这样,不要忘记将 ImageFormat 设置为编码和 ContentType 设置为 http 响应。

希望这可以帮助...

于 2014-06-13T14:05:20.367 回答