旋转图像时背景为黑色 [英] Background is black when rotating an image

查看:347
本文介绍了旋转图像时背景为黑色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to rotate an image using this code:

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

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

For some reason the background after the rotation is black. How can make the background white or transparent?

推荐答案

当您使用 AffineTransformOp时。 filter(src,null)用于创建新图像,新图像使用相同的 ColorModel 作为源图像。

When you are using AffineTransformOp.filter(src, null) for creating new images, the new image uses the same ColorModel as the source image.

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

Your input image is a jpeg, which means it is not transparent, so the destination image is an RGB image, without the alpha (transparency) level.

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

When rotated with such a small angle, the image no longer occupies exactly the same bounds, so the background is visible in its edges and because there is no alpha level, it is normal that the background is black.

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

However, if you save it to a format that supports transparency like gif or png, your image will not display the black background anymore.

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

看看这个以获取更多信息和技巧。

Take a look at this for even more information and tricks.

这是我的图像,轮换到gif:

Here is my image after rotation to gif:

这篇关于旋转图像时背景为黑色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆