【问题标题】:Background is black when rotating an image旋转图像时背景为黑色
【发布时间】:2012-10-09 20:25:45
【问题描述】:

我正在尝试使用此代码旋转图像:

File imgPath = new File("c:\\tmp\\7.jpg");
BufferedImage src = ImageIO.read(imgPath);
AffineTransform tx = new  AffineTransform();

int width = src.getWidth();
int height = src.getHeight();
tx.rotate(radiant ,width, height);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
BufferedImage out = op.filter(src, null);

File outFile = new File("c:\\tmp\\out.jpg");
ImageIO.write(out, "jpg", outFile);

由于某种原因,旋转后的背景是黑色的。 怎样才能让背景变白或透明?

【问题讨论】:

  • 背景为黑色之前是什么颜色?
  • 你把它旋转多少度?我无法从您的代码中看出,因为没有提到辐射值。
  • 没有背景,旋转后旋转前不存在的区域为黑色,
  • 旋转的值为0.02050493823247637
  • 黑色背景和你的图片形状一样吗?

标签: java image rotation


【解决方案1】:

当您使用AffineTransformOp.filter(src, null) 创建新图像时,新图像使用与源图像相同的ColorModel

您的输入图像是 jpeg,这意味着它不透明,因此目标图像是 RGB 图像,没有 alpha(透明度)级别。

当以如此小的角度旋转时,图像不再占据完全相同的边界,因此背景在其边缘可见,并且由于没有 alpha 级别,所以背景为黑色是正常的。

但是,如果您将其保存为支持 gif 或 png 等透明度的格式,则您的图像将不再显示黑色背景。

ImageIO.write(out, "gif", outFile);

完整代码:

    try {
        File imgPath = new File("d:\\downloads\\about.jpg");
        BufferedImage src = ImageIO.read(imgPath);
        AffineTransform tx = new AffineTransform();

        int width = src.getWidth();
        int height = src.getHeight();
        tx.rotate(0.02050493823247637, width, height);
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
        BufferedImage out = op.filter(src, null);

        File outFile = new File("d:\\downloads\\about0.gif");
        ImageIO.write(out, "gif", outFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

查看this 了解更多信息和技巧。

这是我旋转为 gif 后的图像:

【讨论】:

  • 另存为 gif 没有帮助,也许我需要更改源图像中的某些内容?源图像仍然是 jpg。
  • 它确实对我的测试图像有所帮助。但是,您可以使用我链接到的示例中的其他轮换方法。
  • 我做了一个简单的图片完全一样,但我仍然看到黑边,奇怪,我将图像附加到帖子中