【问题标题】:How to set background color when rotating image using thumbnailator使用缩略图旋转图像时如何设置背景颜色
【发布时间】:2020-11-13 05:45:19
【问题描述】:

我正在尝试使用 thumbnailator 库旋转图像。它工作正常,只是我看不到任何设置新图像背景颜色的方法。

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

如果我将图像旋转 45 度,它会使角落变黑。如果我需要设置其他颜色,我该怎么做?

带有黑色背景的旋转图像示例:

【问题讨论】:

  • 实际的image 对象是什么?是BufferedImage吗?或者它是一个图像文件?如果是这样,图像的格式是什么?最后,您是如何创建在此问题中发布的图像文件的?我需要这些提示来追踪发生了什么。 (我是 Thumbnailator 库的作者)
  • 图像是 BufferedImage。生成图像的代码如下所示:Thumbnails.of(image).size(100, 60).rotate(45).imageType(BufferedImage.TYPE_INT_ARGB).outputQuality(0.8D).outputFormat("jpeg").toByteArray();

标签: java image


【解决方案1】:

您可以转换为“中间”图像,然后应用背景颜色。

这主要是未经测试的。

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

【讨论】: