0

这是我的情况: 我有一个控制台应用程序,它以位图格式创建网页截图,然后将其作为字节数组保存到数据库。如何从数据库中返回一个字节数组作为压缩的jpeg/png?

然后我有一个通用处理程序,基本上获取字节数组,然后返回图像(它被设置为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返回,只要它很小。

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

在此先感谢您的回复。

+0

Propably存在对U上的一个答案: http://stackoverflow.com/questions/18609757/how-to-compress-image-byte-array-to-jpeg- png-and-return-imagesource-object – sdrzymala

+0

嗯,这在技术上可能是一个解决方案。但据我所知,你不能在通用处理程序中“返回”某些东西。或者我只是不知道如何。 – webster69

+0

如果dbase中的blob已经被压缩为JPEG文件格式,那么现在的代码只能与'image/jpeg' MIME类型一起正常工作。所以你不能通过对图像进行编码来实现,这已经完成了。只有降低质量或存储较小的图像是一种选择。 –

回答

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,这是无损的 - 如果大多数图像是图形/用户界面/文本,压缩效果可能会更好。如果是这样,不要忘记为编码设置ImageFormat,为http响应设置ContentType。

希望这有助于...

+0

非常感谢,完美的作品! – webster69