解決zxing生成二維碼水印變黑白的問題
在使用ZXing庫生成二維碼并用Thumbnailator庫添加水印時,常常遇到水印顏色變黑白的困擾。這是因為ZXing生成的二維碼默認位深度為1(黑白),而水印圖片通常是彩色圖像。Thumbnailator在疊加水印時,會根據底圖(二維碼)的位深度調整輸出圖像,導致水印顏色信息丟失。
解決方法并非直接修改ZXing的輸出位深度(這會影響二維碼識別),而是先將ZXing生成的二維碼轉換為高位深度圖像,再添加水印。
以下代碼演示了這個過程:首先,使用ZXing生成二維碼,并將其轉換為支持24位真彩色的BufferedImage.TYPE_INT_RGB類型圖像。然后,使用Thumbnailator添加水印,最后保存結果。代碼中用到了toBufferedImage方法將ZXing生成的BitMatrix轉換為BufferedImage,并將其轉換為高位深度圖像。
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.png")); // 使用 Thumbnailator 添加水印 BufferedImage watermarkedImage = Thumbnails.of(convertedImage) .size(300, 300) .watermark(Positions.BOTTOM_RIGHT, watermarkImage, 0.5f) .asBufferedImage(); // 保存最終圖像 ImageIO.write(watermarkedImage, "png", new File("output.png")); } private static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); // ... (toBufferedImage 方法內容與原文相同) ... } }
通過將二維碼轉換為高位深度圖像,確保在添加水印時保留顏色信息,從而解決水印變黑白的問題。 請將 “path/to/watermark/image.png” 替換為您的水印圖片路徑。 toBufferedImage 方法的具體實現與原文相同,此處省略。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END