简体   繁体   中英

How to set background color when rotating image using thumbnailator

I'm trying to rotate an image using thumbnailator library. It works fine except I don't see any way to set background color of the new image.

Thumbnails.of(image).rotate(45).toByteArray()

If I rotate an image 45 degree it makes corners black. If I need to set some other color, how do I do this?

Example of a rotated image with black background:

在此处输入图片说明

You can transform to an "intermediate" image and then apply your background color.

This is mostly untested.

Color newBackgroundColor = java.awt.Color.WHITE;

// apply your transformation, save as new BufferedImage
BufferedImage transImage = Thumbnails.of(image)
        .size(100, 60)
        .rotate(45)
        .outputQuality(0.8D)
        .outputFormat("jpeg")
        .asBufferedImage();

// Converts image to plain RGB format
BufferedImage newCompleteImage = new BufferedImage(transImage.getWidth(), transImage.getHeight(),
        BufferedImage.TYPE_INT_ARGB);
newCompleteImage.createGraphics().drawImage(transImage, 0, 0, newBackgroundColor, null);

// write the transformed image with the desired background color
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newCompleteImage, "jpeg", baos);

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