java - 旋转图像时背景为黑色

标签 java image rotation

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

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

由于某种原因,旋转后的背景是黑色的。 如何让背景变成白色或透明?

最佳答案

当您使用 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 image after rotation

关于java - 旋转图像时背景为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12799052/

相关文章:

javascript - 如何在 View MVC 中更改 img src

image - rust 图像发布请求

Java奇怪的计算

css - 使用css围绕中心文本位置旋转svg文本

java - 如何在 Java 应用程序中实现基于声明的身份验证?

java - 如何使用 Android Gradle 插件 3.0.0+ 来操作变体输出?

java - 在spring rest multipart image upload api中获取BAD REQUEST

java - 如何在不知道 key 的情况下使用java解析JSON对象?

html - 调整显示:table-row的div中的img高度

Java - 旋转图像总是失败