简体   繁体   English

C#图像压缩-导致图像裁剪

[英]C# Image Compression - Causing Image to Crop

I'm working on compressing our images that are uploaded using a Telerik RadAsyncUpload control. 我正在压缩使用Telerik RadAsyncUpload控件上传的图像。

On the backend I get the uploaded file input stream (Stream class) and pass it to this compression method: 在后端,我获取上载的文件输入流(Stream类),并将其传递给此压缩方法:

    private byte[] GetCompressedImage(Stream stream, ImageFormat format)
    {
        ImageCodecInfo imgCodec = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == format.Guid);

        EncoderParameters codecParams = new EncoderParameters(1);
        codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 70L);

        using (Bitmap bitmap = new Bitmap(stream))
        {
            using (var ms = new MemoryStream())
            {
                bitmap.Save(ms, imgCodec, codecParams);
                return ms.ToArray();
            }
        }
    }

I then add the bytes to the a list of bytes that represents each file uploaded (this control allows multiples). 然后,我将字节添加到代表每个上载文件的字节列表中(此控件允许多个)。 We then pass it on to the FTP folder, etc. 然后,将其传递到FTP文件夹等。

I can't for the life of me figure out why it's cropping the image rather than compressing. 我一辈子都无法弄清楚为什么它会裁剪图像而不是压缩图像。 The bytes are smaller, width and height are the same, and it just doesn't show whatever a portion of the image. 字节较小,宽度和高度相同,并且只是不显示图像的任何部分。

Any ideas? 有任何想法吗?

I finally got it working. 我终于让它工作了。 I moved the method into where we pass in the list of bytes (aka files uploaded) and passed in an Image object to the method rather than the stream. 我将方法移入字节列表(也就是上传的文件)的传递位置,并将Image对象传递给方法而不是流。

    /// <summary>
    /// Compress the image
    /// </summary>
    /// <param name="stream">Image stream</param>
    /// <param name="format">Image format</param>
    /// <returns>Byte array representing the image</returns>
    public static byte[] GetCompressedImage(Image original, ImageFormat format)
    {
        ImageCodecInfo imgCodec = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == format.Guid);

        EncoderParameters codecParams = new EncoderParameters(1);
        codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 70L);

        using (var bitmap = new Bitmap(original))
        {
            using (var ms = new MemoryStream())
            {
                bitmap.Save(ms, imgCodec, codecParams);
                return ms.ToArray();
            }
        }
    }

Thanks for the suggestions! 感谢您的建议!

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

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