旋转中增加图像大小的原因是什么

本文关键字:是什么 增加 图像 旋转 | 更新日期: 2023-09-27 18:35:23

我有一个 c# 应用程序,其中包含一个图像库,我可以在其中显示一些图片。此图库具有一些功能,包括左右旋转。一切都很完美,但是当我从图库中选择图片并按旋转按钮(无论向左或向右旋转)时,图片的大小显着增加。应该提到的是,图片的格式是JPEG。

旋转前的图片尺寸 : 278 kb

旋转后图片尺寸 : 780 kb

我的旋转代码就像下面一样:

 public Image apply(Image img)
    {  
        Image im = img;
        if (rotate == 1) im.RotateFlip(RotateFlipType.Rotate90FlipNone);
        if (rotate == 2) im.RotateFlip(RotateFlipType.Rotate180FlipNone);
        if (rotate == 3) im.RotateFlip(RotateFlipType.Rotate270FlipNone);
        //file size is increasing after RotateFlip method
        if (brigh != DEFAULT_BRIGH ||
            contr != DEFAULT_CONTR ||
            gamma != DEFAULT_GAMMA)
        {
            using (Graphics g = Graphics.FromImage(im))
            {
                float b = _brigh;
                float c = _contr;
                ImageAttributes derp = new ImageAttributes();
                derp.SetColorMatrix(new ColorMatrix(new float[][]{
                        new float[]{c, 0, 0, 0, 0},
                        new float[]{0, c, 0, 0, 0},
                        new float[]{0, 0, c, 0, 0},
                        new float[]{0, 0, 0, 1, 0},
                        new float[]{b, b, b, 0, 1}}));
                derp.SetGamma(_gamma);
                g.DrawImage(img, new Rectangle(Point.Empty, img.Size),
                    0, 0, img.Width, img.Height, GraphicsUnit.Pixel, derp);
            }
        }
        return im; 
    }

问题出在哪里?

旋转中增加图像大小的原因是什么

在您的情况下,对

im应用RotateFlip会将ImageFormatJpeg更改为MemoryBmp。默认情况下,当您保存图像时,它将使用默认ImageFormat 。这将是im.RawFormat返回的格式

如果检查 GUID im.RawFormat.Guid

旋转翻转之前

{b96b3cae-0728-11d3-9d7b-0000f81ef32e}这与ImageFormat.Jpeg.Guid相同

旋转翻转后

{b96b3caa-0728-11d3-9d7b-0000f81ef32e}这与ImageFormat.MemoryBmp.Guid相同

在保存图像时,将ImageFormat作为第二个参数传递,这将确保它使用正确的格式。如果没有提到,它将是im.RawFormat

所以如果你想在保存电话时另存为 jpeg

im.Save("filename.jpg", ImageFormat.Jpeg);

这次文件大小应小于原始大小。

另请注意ImageFormat位于System.Drawing.Imaging命名空间

注意

若要控制 jpeg 的质量,请使用重载的 Save 方法,如此 MSDN 链接中所述


根据评论进行编辑

好的,假设您使用的是SQL Server,您必须有一个image数据类型列(建议使用varbinary(max)而不是image因为将来它会过时(阅读MSDN帖子)

现在进入步骤

1) read the contents as a stream / byte[] array
2) convert this to Image
3) perform rotate operation on the Image
4) convert this Image back to stream / byte[] array
5) Update the database column with the new value

两个原因:

    JPEG
  1. 压缩/编码/采样未像原始 JPEG 那样优化。
  2. JPEG 不透明。当图像未旋转 90/180/270 度时,图像的矩形边界会变大。

您应该在更改图像之前保留原始ImageFormat,并通过原始图像格式保存到文件中。像下面的代码:

using (Image image = Image.FromFile(filePath))
{
    var rawFormat = image.RawFormat;
    image.RotateFlip(angel);
    image.Save(filePath, rawFormat);
}