我试图在ASP.NET MVC中支持旋转JPEG图片(以90度为单位)。我尝试使用System.Drawing(GDI +)来实现,但是遇到了问题。
我尝试使用Image.RotateFlip,它可以旋转图像,但会导致质量损失。即使编码器质量为100,旋转后的图像上仍然有可见的伪影,这些伪影在原始图像上不存在,使用其他程序(如Gimp等)旋转时也不会出现。
我尝试使用Image.RotateFlip,它可以旋转图像,但会导致质量损失。即使编码器质量为100,旋转后的图像上仍然有可见的伪影,这些伪影在原始图像上不存在,使用其他程序(如Gimp等)旋转时也不会出现。
using (Image image = Image.FromFile("C:\\source.jpg")) {
ImageFormat sourceFormat = image.RawFormat;
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
EncoderParameters encoderParams = null;
try {
if (sourceFormat == ImageFormat.Jpeg) {
encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
}
image.Save("C:\\target.jpg", GetEncoder(sourceFormat), encoderParams);
} finally {
if (encoderParams != null)
encoderParams.Dispose();
}
}
我找到了一篇有关于如何无损转换JPEG的文章(链接)。看起来在.NET中使用Encoder.Transformation
是一个选项,但是无论图像的尺寸是否是16的倍数,我都无法使它旋转我的JPEG测试图片。
using (Image image = Image.FromFile("C:\\source.jpg")) {
ImageFormat sourceFormat = image.RawFormat;
EncoderParameters encoderParams = null;
try {
if (sourceFormat == ImageFormat.Jpeg) {
encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Transformation,
(long)EncoderValue.TransformRotate90);
}
image.Save("C:\\target.jpg", GetEncoder(sourceFormat), encoderParams);
} finally {
if (encoderParams != null)
encoderParams.Dispose();
}
}
有人知道如何在.NET中使用上述方法或其他方法成功地将JPEG以90度为单位旋转,而最小化或不损失质量吗?谢谢。
此外,这是我实现的GetEncoder
:
private ImageCodecInfo GetEncoder(ImageFormat format) {
foreach (var info in ImageCodecInfo.GetImageEncoders())
if (info.FormatID == format.Guid)
return info;
return null;
}
编辑:
我更新了上面的代码以更好地匹配我的实际代码。错误在以下行中:
if (sourceFormat == ImageFormat.Jpeg) {
它应该是:
if (sourceFormat.Guid == ImageFormat.Jpeg.Guid) {