简体   繁体   中英

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.

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.

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.

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

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图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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