Graphics2D 画图透明通道处理

    技术2023-08-04  66

    为了生成海报画图,有的图片是带有透明通道的。但是生成后就处理成黑色背景

    网上搜了好多都不符合,为了后面小伙伴的方便。特分享下~

    下图是生成的效果

    原图                                           

    没有添加透明通道生成的图

    重点的核心代码来了:

    /** * 缩放图片+透明 * * @param image 需要缩放的图片 * @param width 宽 * @param height 高 * @return BufferedImage */ private static BufferedImage resize(BufferedImage image, int width, int height) { java.awt.Image img = image.getScaledInstance(width, height, java.awt.Image.SCALE_FAST); BufferedImage newBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = newBufferedImage.createGraphics(); graphics.drawImage(img, 0, 0, null); graphics.dispose(); return newBufferedImage; }

    调用

    image = resize(image, width, height);
    Processed: 0.009, SQL: 10