简体   繁体   English

使用缩略图旋转图像时如何设置背景颜色

[英]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.如果我将图像旋转 45 度,它会使角落变黑。 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);

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

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