用ZXing生成二维码后使用Thumbnailator添加水印,水印变成黑白,该如何解决?

ZXing生成的二维码位深度只有1,而水印则是32,似乎Thumbnailator是依据被加水印图片的位深度决定输出图片位深度,有方法让ZXing一开始就输出高位深度的图片(前提是不改变储存信息的像素的点),或者制定Thumbnailator输出图片的位深度吗?


回答:

你可以先生成二维码,然后将它转换为高位深度的 BufferedImage,最后使用 Thumbnailator 添加水印就可以了:

import com.google.zxing.*;

import com.google.zxing.common.BitMatrix;

import com.google.zxing.qrcode.QRCodeWriter;

import net.coobird.thumbnailator.Thumbnails;

import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

public class QRCodeWatermarkExample {

public static void main(String[] args) throws WriterException, IOException {

// 生成二维码

QRCodeWriter qrCodeWriter = new QRCodeWriter();

BitMatrix bitMatrix = qrCodeWriter.encode("https://example.com", BarcodeFormat.QR_CODE, 300, 300);

BufferedImage qrCodeImage = toBufferedImage(bitMatrix);

// 将二维码转换为高位深度的 BufferedImage

BufferedImage convertedImage = new BufferedImage(qrCodeImage.getWidth(), qrCodeImage.getHeight(), BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = convertedImage.createGraphics();

g2d.drawImage(qrCodeImage, 0, 0, null);

g2d.dispose();

// 读取水印图片

BufferedImage watermarkImage = ImageIO.read(new File("path/to/watermark/image.jpg"));

// 使用 Thumbnailator 添加水印

BufferedImage watermarkedImage = Thumbnails.of(convertedImage)

.size(300, 300)

.watermark(Positions.BOTTOM_RIGHT, watermarkImage, 0.5f)

.asBufferedImage();

// 保存最终图像

ImageIO.write(watermarkedImage, "png", new File("output.jpg"));

}

private static BufferedImage toBufferedImage(BitMatrix matrix) {

int width = matrix.getWidth();

int height = matrix.getHeight();

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);

for (int x = 0; x < width; x++) {

for (int y = 0; y < height; y++) {

image.setRGB(x, y, matrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());

}

}

return image;

}

}

以上是 用ZXing生成二维码后使用Thumbnailator添加水印,水印变成黑白,该如何解决? 的全部内容, 来源链接: utcz.com/p/945120.html

回到顶部