mas*_*ani 3 c# image rotation image-resizing
我有一个ac#应用程序,其中包含一个图像库,我在其中显示一些图片.这个画廊有一些功能,包括左右旋转.一切都很完美但是当我从画廊选择一张图片并按下旋转按钮(无论左右旋转)时,图片的大小会显着增加.应该提到图片的格式是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;
}
Run Code Online (Sandbox Code Playgroud)
问题是什么?提前致谢.
在你的情况适用RotateFlip
于im
正在改变ImageFormat
从Jpeg
到MemoryBmp
.保存图像时默认情况下,它将使用默认值ImageFormat
.这将是返回的格式im.RawFormat
如果你检查GUID im.RawFormat.Guid
在RotateFlip之前
{b96b3cae-0728-11d3-9d7b-0000f81ef32e}与...相同 ImageFormat.Jpeg.Guid
RotateFlip之后
{b96b3caa-0728-11d3-9d7b-0000f81ef32e}与...相同 ImageFormat.MemoryBmp.Guid
在保存图像时ImageFormat
,将第二个参数传递给它,以确保它使用正确的格式.如果没有提到它将成为一个im.RawFormat
所以如果你想在保存电话时保存为jpeg
im.Save("filename.jpg", ImageFormat.Jpeg);
Run Code Online (Sandbox Code Playgroud)
这次文件大小应小于原始大小.
另请注意ImageFormat
,在System.Drawing.Imaging
命名空间中
注意
要控制jpeg的质量,请使用此MSDN链接中提到的重载Save方法
编辑基于评论
好的,假设您正在使用SQL Server,您必须拥有一个image
数据类型列(建议使用varbinary(max)
而不是image
将来使用它将成为obselete(阅读MSDN Post)
现在到了步骤
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
Run Code Online (Sandbox Code Playgroud)