2010-03-19 25 views
2

我遇到图像缩放问题。当我使用下面的代码来缩放图像时,它会以图像底部或右侧的一条线结束。Java:使用AffineTransform缩放图像时出现线条

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); 

原始图像

enter image description here

缩放后的图像

enter image description here

有谁知道为什么线出现?

谢谢!

编辑:

添加了完整的方法代码:

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_ *常量。

谢谢!

+0

我跑你的代码(使用作为输入图像),它看起来很好。你在用什么'scaleWidth' /'scaleHeight'?你如何加载图像?你如何显示/保存它? – Ash 2010-03-19 21:23:53

+0

我添加了完整的方法 - 感谢。 – Malakim 2010-03-21 07:37:32

回答

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

+0

添加了完整的方法 - 我使用JDK 1.6.0_18。 谢谢。 – Malakim 2010-03-21 07:37:14

+0

这可能是它,我会尝试你的建议,看看他们解决问题。 谢谢! – Malakim 2010-03-23 07:11:05