Compress image without saving it

被刻印的时光 ゝ 提交于 2019-12-11 09:57:22

问题


I am using the following code to compress an image and it does a nice job but I want to use the compressed image not save it. So right now I have to save the image then read it in again which is slow. Is there a way of compressing it with out saving it.

    private void compress(System.Drawing.Image img, long quality, ImageCodecInfo codec)
    {
        EncoderParameters parameters = new EncoderParameters(1);
        parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
        img.Save("check1.jpg", codec, parameters);
    }

    private static ImageCodecInfo GetCodecInfo(string mimeType)
    {
        foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
            if (encoder.MimeType == mimeType)
                return encoder;
        throw new ArgumentOutOfRangeException(
            string.Format("'{0}' not supported", mimeType));
    }

回答1:


There is an overload that takes a Stream so you can save it straight to a MemoryStream and won't need to save to disk/reload.

EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);

var ms = new MemoryStream();
img.Save(ms, codec, parameters);

//Do whatever you need to do with the image
//e.g.
img = Image.FromStream(ms);

The reason you're getting the "Parameter not valid" exception you mention in the comments is because the image isn't being disposed of before you try to call FromStream, so you'll need to dispose it. Also, I don't know how you're calling this method, but you should probably update it to return the MemoryStream.

private void compress(System.Drawing.Image img, long quality, ImageCodecInfo codec)
{
    EncoderParameters parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);

    var ms = new MemoryStream();
    img.Save(ms, codec, parameters);
    return ms;
}

public void MyMethod()
{
    MemoryStream ms;
    using(var img = Image.FromFile("myfilepath.img"))
    {
        ms = compress(img, /*quality*/, /*codec*/);
    }

    using(var compressedImage = Image.FromStream(ms))
    {
        //Use compressedImage
    }
}

Notice how I return ms from compress and capture it. Also, more importantly, how we wrap the initial img in a using statement which will dispose the file handle correctly, and after that gets disposed create the second compressedImage which is also in a using so it will also get disposed of properly when you're done.



来源:https://stackoverflow.com/questions/33393975/compress-image-without-saving-it

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