以最小的质量损失在.NET中旋转JPG [英] Rotating JPEGs in .NET with minimal loss of quality

查看:40
本文介绍了以最小的质量损失在.NET中旋转JPG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试支持从ASP.NET MVC(以90度为增量)旋转JPEG图像。我正在尝试使用System.Drawing(GDI+),但遇到问题。

我尝试使用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();
    }
}

我在transforming a JPEG without loss of information上找到一篇文章。使用Encoder.Transformation似乎是.NET的一个选项--然而,我根本无法使用它来使我的任何JPEG测试图像旋转,无论其尺寸是否为16的倍数。

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中成功地以90度增量旋转JPEG,而质量损失最小或没有损失?谢谢。

另外,下面是我的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) {

推荐答案

感谢您确认我发布的代码工作正常。这帮助我隔离了我的问题。我现在觉得自己很蠢。我的实际代码在设置encoderParams之前检查了图像格式-但它有一个错误:

if (sourceFormat == ImageFormat.Jpeg) {
    // set encoderParams here

我发现上面的条件总是假的,所以没有设置encoderParams。解决方法很简单:

if (sourceFormat.Guid == ImageFormat.Jpeg.Guid) {

这篇关于以最小的质量损失在.NET中旋转JPG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆