简体   繁体   English

压缩流中的图像

[英]Compress image from stream

I am storing images in database, before I store them, i am resizing them. 我将图像存储在数据库中,然后再存储它们,然后调整它们的大小。

However, resizing, doesnt compress the image. 但是,调整大小不会压缩图像。 Stream is same stream. 流是相同的流。 I want to be able to compress the image as well. 我也希望能够压缩图像。

How can I compress images which are stored in database as stream and returned to request as follows? 如何压缩以流形式存储在数据库中并返回给请求的图像,如下所示?

    public ActionResult ViewImage(int id, string imageType ="image")
    {
        ContestImage contestImage = GetContestImage(id);

        byte[] fileContent;
        string mimeType;
        string fileName;

        if (imageType == "thumb")
        {
            fileContent = contestImage.ThumbNail.Image;
            mimeType = contestImage.ThumbNail.ImageMimeType;
            fileName = contestImage.ThumbNail.ImageFileName;
        }
        else if (imageType == "image")
        {
            fileContent = contestImage.Image.Image;
            mimeType = contestImage.Image.ImageMimeType;
            fileName = contestImage.Image.ImageFileName;
        }


        return File(fileContent, mimeType, fileName);
    }

public class UserImage
{
    public virtual int Id { set; get; }
    public virtual byte[] Image { set; get; }
    public virtual string ImageMimeType { set; get; }
    public virtual string ImageFileName { set; get; }
}

ContestImage has UserImage object. ContestImage具有UserImage对象。

从数据库存储和检索图像时,您是否尝试过使用GZipStream

Two main approaches spring to mind: 我想到了两种主要方法:

  • Load the data as an Image and serialize it (to a memory stream) in a compressed file format (eg png or jpeg) 将数据作为图像加载并以压缩文件格式(例如png或jpeg)将其序列化(存储到内存流)

  • Serialize the data (to a memory stream) via a compressing stream such as DeflateStream. 通过压缩流(例如DeflateStream)将数据序列化(到内存流)。

Once you have the data in a MemoryStream, you can use MemoryStream.ToArray() to convert it back to a straight byte[] buffer to pass to your database. 一旦将数据存储在MemoryStream中,就可以使用MemoryStream.ToArray()将其转换回纯字节[]缓冲区以传递到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM