Image compression is not working

柔情痞子 提交于 2020-01-25 11:34:24

问题


I have an operation on the site that takes crops an image, however the resultant, cropped image is coming out significantly larger in terms of file size (original is 24k and the cropped image is like 650k). So I found that I need to apply some compression to the image before saving it. I came up with the following:

public static System.Drawing.Image CropImage(System.Drawing.Image image, Rectangle cropRectangle, ImageFormat format)
{
    var croppedImage = new Bitmap(cropRectangle.Width, cropRectangle.Height);
    using (var g = Graphics.FromImage(croppedImage))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(
            image, 
            new Rectangle(new Point(0,0), new Size(cropRectangle.Width, cropRectangle.Height)), 
            cropRectangle, 
            GraphicsUnit.Pixel); 
        return CompressImage(croppedImage, format);
    }
}

public static System.Drawing.Image CompressImage(System.Drawing.Image image, ImageFormat imageFormat)
{
    var bmp = new Bitmap(image);
    var codecInfo = EncoderFactory.GetEncoderInfo(imageFormat);
    var encoder = System.Drawing.Imaging.Encoder.Quality;
    var parameters = new EncoderParameters(1);
    var parameter = new EncoderParameter(encoder, 10L);
    parameters.Param[0] = parameter;

    using (var ms = new MemoryStream())
    {
        bmp.Save(ms, codecInfo, parameters);
        var resultImage = System.Drawing.Image.FromStream(ms);
        return resultImage;
    }
}

I set the quality low just to see if there was any change at all. There isn't. The crop is being saved correctly appearance-wise but compression is a no joy. If I bypass CompressImage() altogether, neither the file size nor the image quality appear to be any different.

So, 2 questions. Why is nothing happening? Is there a simpler way to compress the resultant image to "web-optimize" similar to how photoshop saves web images (I thought it just stripped a lot of info out of it to reduce the size).


回答1:


Your problem is you must 'compress' (really encode) the image as you save it, not before you save it. An Image object in your program is always uncompressed.

By saving to the MemoryStream and reading back out from the stream will encode the image and then decode it back to the same size again (with some quality loss in the process if you are using JPEG). However, if you save it to a file with the compression parameters, you will get a compressed image file.

Using this routine with JPEG quality level 90 on a 153 KB source image gives an output image of 102 KB. If you want a smaller file size (with more encoding artifacts) change the encoder parameter to something smaller than 90.

public static void SaveJpegImage(System.Drawing.Image image, string fileName)
{
    ImageCodecInfo codecInfo = ImageCodecInfo.GetImageEncoders()
        .Where(r => r.CodecName.ToUpperInvariant().Contains("JPEG"))
        .Select(r => r).FirstOrDefault();

    var encoder = System.Drawing.Imaging.Encoder.Quality;
    var parameters = new EncoderParameters(1);
    var parameter = new EncoderParameter(encoder, 90L);
    parameters.Param[0] = parameter;

    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        image.Save(fs, codecInfo, parameters);
    }
}



回答2:


I believe you shouldn't dispose of the MemoryStream while you are using an image created using Image.FromStream that refers to the stream. Creating a Bitmap directly from the stream also doesn't work.

Try this:

private static Image CropAndCompressImage(Image image, Rectangle rectangle, ImageFormat imageFormat)
{
    using(Bitmap bitmap = new Bitmap(image))
    {
        using(Bitmap cropped = bitmap.Clone(rectangle, bitmap.PixelFormat))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                cropped.Save(memoryStream, imageFormat);
                return new Bitmap(Image.FromStream(memoryStream));
            }
        }
    }
}


来源:https://stackoverflow.com/questions/21591848/image-compression-is-not-working

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