【问题标题】:How do I return a byte array from the db as a compressed jpeg/png?如何从数据库返回一个字节数组作为压缩的 jpeg/png?
【发布时间】:2014-06-13 22:15:57
【问题描述】:

这是我的情况: 我有一个控制台应用程序,它以位图格式创建网页屏幕截图,然后将其作为字节数组保存到数据库中。

然后我有一个通用处理程序,它基本上获取字节数组,然后返回图像(它被设置为 html 图像源)。代码如下:

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

(那段代码不是我自己写的)

尽管图像当然仍以位图的形式返回,而且尺寸太大。 这就是为什么我想将它作为压缩的 jpg 或 png 返回,只要它很小。

所以我的问题是:有什么可能性可以做到这一点而不必将图像直接保存到文件系统?

提前感谢您的回复。

【问题讨论】:

  • 嗯,这在技术上可能是一个解决方案。但据我所知,您不能只在通用处理程序中“返回”某些内容。或者我只是不知道怎么做。
  • 如果 dbase 中的 blob 已压缩为 JPEG 文件格式,您现在拥有的代码只能与 image/jpeg MIME 类型一起正常工作。所以你不能通过编码图像来取得成功,这已经完成了。仅降低质量或存储较小的图像是一种选择。
  • 好的。降低质量很好,但是如何从字节数组中做到这一点?

标签: c# bytearray image-compression image-conversion generic-handler


【解决方案1】:

下面的 sn-p 应该会让你更接近你的目标。

假设从数据库中检索到的字节数组可以被 .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 和为 http 响应设置 ContentType。

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 2018-10-21
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2011-11-15
    • 2015-12-27
    相关资源
    最近更新 更多