【问题标题】:Java: Line appears when using AffineTransform to scale imageJava:使用 AffineTransform 缩放图像时出现线条
【发布时间】:2010-03-19 10:49:20
【问题描述】:

我遇到了图像缩放问题。当我使用以下代码缩放图像时,它会在图像底部或右侧出现一条线。

double scale = 1;
if (scaleHeight >= scaleWidth) {
    scale = scaleWidth;
} else {
    scale = scaleHeight;
}
AffineTransform af = new AffineTransform();
af.scale(scale, scale);

AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage bufferedThumb = operation.filter(img, null);

原图

缩放后的图像

有人知道为什么会出现这条线吗?

谢谢!

编辑:

添加了完整的方法代码:

public static final int SPINNER_MAX_WIDTH = 105;
public static final int SPINNER_MAX_HEIGHT = 70;

public void scaleImage(BufferedImage img, int maxWidth, int maxHeight, String fileName) {
    double scaleWidth = 1;
    double scaleHeight = 1;

    if (maxHeight != NOT_SET) {
        if (img.getHeight() > maxHeight) {
            scaleHeight = (double) maxHeight / (double) img.getHeight();
        }
    }

    if (maxWidth != NOT_SET) {
        if (img.getWidth() > maxWidth) {
            scaleWidth = (double) maxWidth / (double) img.getWidth();
        }
    }

    double scale = 1;

    if (scaleHeight >= scaleWidth) {
        scale = scaleWidth;
    } else {
        scale = scaleHeight;
    }

    AffineTransform af = new AffineTransform();
    af.scale(scale, scale);

    AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    BufferedImage bufferedThumb = operation.filter(img, null);

    if (bufferedThumb != null) {
        File imageFile = new File(fileName);
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        try {
            ImageIO.write(bufferedThumb, fileType, imageFile);
        } catch (IOException e) {
            logger.error("Failed to save scaled image: " + fileName + "\n" + e.getMessage());
        }
    }
}

方法调用中的 maxWidth 和 maxHeight 参数设置为 SPINNER_MAX_* 常量。

谢谢!

【问题讨论】:

  • 我运行了您的代码(使用您的图像作为输入),它看起来不错。你用什么scaleWidth/scaleHeight?你是如何加载图像的?你是如何显示/保存它的?
  • 我添加了完整的方法 - 谢谢。

标签: java image-processing java-2d affinetransform


【解决方案1】:

你能否给我们剩下的代码 - 你如何操作bufferedThumb,因为如果你只是将它保存到一个文件中应该没问题。

ImageIO.write(bufferedThumb, "PNG", new File("img.png"));

你用的是什么java版本?

已编辑:

你可以尝试像这样明确地构造最终图像:

BufferedImage bufferedThumb = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
operation.filter(img, bufferedThumb);

确定正在使用什么颜色模式。

我认为您的问题可能与此错误有关: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6725106

另一件事是可能使用不同的插值类型,例如:

AffineTransformOp.TYPE_BILINEAR

有关更多信息,请查看: http://www.dpreview.com/learn/?/key=interpolation

【讨论】:

  • 添加了完整的方法 - 我使用 JDK 1.6.0_18。谢谢。
  • 大概就是这样,我会试试你的建议,看看他们是否能解决问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 2021-07-25
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
相关资源
最近更新 更多