简体   繁体   English

旋转图像时背景为黑色

[英]Background is black when rotating an image

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? 如何使背景白色或透明?

When you are using AffineTransformOp.filter(src, null) for creating new images, the new image uses the same ColorModel as the source image. 当您使用AffineTransformOp.filter(src, null)创建新图像时,新图像使用与源图像相同的ColorModel

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. 您输入的图像是jpeg,这意味着它不是透明的,因此目标图像是RGB图像,没有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. 当以较小的角度旋转时,图像不再占据完全相同的边界,因此背景在其边缘可见,并且由于没有alpha电平,因此背景为黑色是正常的。

However, if you save it to a format that supports transparency like gif or png, your image will not display the black background anymore. 但是,如果将其保存为支持gif或png等透明度的格式,则图像将不再显示黑色背景。

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

The full code: 完整代码:

    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. 看看这个以获得更多信息和技巧。

Here is my image after rotation to gif: 这是我旋转到gif后的图像: 旋转后的gif图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM