1

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?

konqi
  • 5,137
  • 3
  • 34
  • 52
Asaf Zinger
  • 93
  • 1
  • 5

1 Answers1

0

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 image after rotation

Community
  • 1
  • 1
Dan D.
  • 32,246
  • 5
  • 63
  • 79
  • saving as gif did not help, maybe I need to change something in the source image? the source image is still jpg. – Asaf Zinger Oct 09 '12 at 12:04
  • It did help me with my test image. However, you can use the other rotation approach as in the example I linked to. – Dan D. Oct 09 '12 at 12:09
  • I did exactly the same with a simple picture but I still see the black edges, strange, I will attach the image to the post – Asaf Zinger Oct 09 '12 at 12:22