旋转 BufferedImage 会改变它的颜色

Rotating BufferedImage changes its colors

我正在尝试编写 class 以在 x 和 y 方向上缝合雕刻图像。 x 方向有效,为了减少 y 方向,我考虑简单地将图像旋转 90° 并 运行 在已经重新缩放的图像上使用相同的代码(仅在 x 方向),然后将其旋转回原来的位置初始状态。

我用 AffineTransform 找到了一些东西并试了一下。它实际上产生了一个旋转的图像,但是颜色弄乱了,我不知道为什么。

这是全部代码:

import java.awt.image.BufferedImage;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.io.File;
import java.io.IOException;
import javafx.scene.paint.Color;
import javax.imageio.ImageIO;


public class example {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    // TODO code application logic here

    BufferedImage imgIn = ImageIO.read(new File("landscape.jpg"));
    BufferedImage imgIn2 = imgIn;

    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.PI/2, imgIn2.getWidth() / 2, imgIn2.getHeight() / 2);//(radian,arbit_X,arbit_Y)

    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
    BufferedImage last = op.filter(imgIn2, null);//(sourse,destination)
    ImageIO.write(last, "JPEG", new File("distortedColors.jpg"));
}

}

只需更改
中的文件名 BufferedImage imgIn = ImageIO.read(new File("landscape.jpg")); 试试吧。

执行时,您会得到 4 张图像:一张热图、一张有接缝的图像和一张重新缩放的图像。最后一张图片是一个测试,看看旋转是否有效,它应该显示旋转的图像,但颜色失真...

不胜感激!

编辑:

由于将 null 传递给 op.filter(imgIn2, null);,似乎发生了颜色转换。

如果你这样改变它应该可以工作:

BufferedImage last = new BufferedImage( imgIn2.getWidth(), imgIn2.getHeight(), imgIn2.getType() );
op.filter(imgIn2, last );

问题出在 AffineTransformOp 您需要:

AffineTransformOp.TYPE_NEAREST_NEIGHBOR

而不是您现在拥有的 BILINEAR。

文档中的第二段对此进行了提示。

This class uses an affine transform to perform a linear mapping from 2D coordinates in the source image or Raster to 2D coordinates in the destination image or Raster. The type of interpolation that is used is specified through a constructor, either by a RenderingHints object or by one of the integer interpolation types defined in this class. If a RenderingHints object is specified in the constructor, the interpolation hint and the rendering quality hint are used to set the interpolation type for this operation.

The color rendering hint and the dithering hint can be used when color conversion is required. Note that the following constraints have to be met: The source and destination must be different. For Raster objects, the number of bands in the source must be equal to the number of bands in the destination.

所以这行得通

AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

根据 bhavya 所说...

保持简单,您应该使用操作预期的维度:

AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage destinationImage = op.filter(bImage, op.createCompatibleDestImage(bImage, null));