1. 背景の紹介
最近、定期刊行物を作成する際にQRコード生成機能を利用させていただきましたが、実は8~9年前にもQRコード生成の練習をしたことがあり、その際に幅やサイズをカスタマイズできるオンライン生成の例も作りました。高さ、内容、ロゴの小さいアイコン(小さいアイコンの位置は複数選択可能)、今回使ってみると、以前のQRコードでは白枠の問題があったことが分かりました。実際に動作するので、今回は解決策を記録し、ソース コードを変更する方法を使用してソース コードをプロジェクトにコピーし (パッケージ パス名を jar と一貫性を保ちます)、IDE を使用して最初にプロジェクトをロードします。ソース コードを変更して有効にするという目的を達成するために、jar 内のクラス ファイルの特性をカバーするクラスの特性。(PS: java -cp が優先ロード順序もサポートしているときに指定されたクラスパスなど、起動スクリプトを使用してプログラムを実行する場合、詳細については、このサイトが提供する Spring Boot アプリケーションのパッケージ化の章を参照してください)
話に戻りますが、この記事は主に、zxing コンポーネントを使用して QR コードを生成する際の白枠の問題を解決することを目的としています。いわゆる白枠とは、生成される QR コード画像のサイズが実際に設定されたサイズではないことを意味し、一定の大きさの白い余白が生じます。今回の実践で、設定パラメータ「EncodeHintType.MARGIN」が0の場合は無効であることが分かりました。多くの専門記事でもQRコードのグラフィック品質を優先する説明がされていました。記事によっては、最初に白い余白のある画像を生成し、画像拡大技術を利用してQRコードの画像を一定の比率で拡大縮小するという方法も使われています。ホワイトマージンの問題。これは、インターネット上の多くの情報記事で優先的に採用されている解決策でもあります。
2. 導入プロセス
今回選択した方法は比較的単純な方法で、ソースコードを直接変更して「EncodeHintType.MARGIN」が現在 0 に設定されているかどうかを確認します。設定されていない場合は何も行われません。設定されている場合は、変更されたソースが変更後のソースコードは以下のとおりです。
2.1 pom.xml 座標
<!-- 二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.1</version>
</dependency>
2.2 ソースコードクラス QRCodeWriter
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.qrcode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;
import java.util.Map;
/**
* This object renders a QR Code as a BitMatrix 2D array of greyscale values.
*
* @author [email protected] (Daniel Switkin)
*/
public final class QRCodeWriter implements Writer {
private static final int QUIET_ZONE_SIZE = 4;
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
throws WriterException {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) throws WriterException {
if (contents.isEmpty()) {
throw new IllegalArgumentException("Found empty contents");
}
if (format != BarcodeFormat.QR_CODE) {
throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' +
height);
}
ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
int quietZone = QUIET_ZONE_SIZE;
if (hints != null) {
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}
if (hints.containsKey(EncodeHintType.MARGIN)) {
quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
}
QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);
return renderResult(code, width, height, quietZone);
}
// Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
// 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
private static BitMatrix renderResult(QRCode code, int width, int height, int quietZone) {
ByteMatrix input = code.getMatrix();
if (input == null) {
throw new IllegalStateException();
}
int inputWidth = input.getWidth();
int inputHeight = input.getHeight();
int qrWidth = inputWidth + (quietZone * 2);
int qrHeight = inputHeight + (quietZone * 2);
int outputWidth = Math.max(width, qrWidth);
int outputHeight = Math.max(height, qrHeight);
int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight);
/**1.改动点begin**/
if (quietZone == 0) {
outputWidth = qrWidth * multiple;
outputHeight = qrWidth * multiple;
}
/**1.改动点end**/
// Padding includes both the quiet zone and the extra white pixels to accommodate the requested
// dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
// If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
// handle all the padding from 100x100 (the actual QR) up to 200x160.
int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
int topPadding = (outputHeight - (inputHeight * multiple)) / 2;
/**2.改动点begin**/
if (quietZone == 0) {
leftPadding = 0 ;
topPadding = 0;
}
/**2.改动点end**/
BitMatrix output = new BitMatrix(outputWidth, outputHeight);
for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY) == 1) {
output.setRegion(outputX, outputY, multiple, multiple);
}
}
}
return output;
}
}
説明: ソース コードの変更は 2 か所です。コメントを参照してください。主なロジックは、渡された MARGIN 値が 0 であるかどうかを判断し、0 であれば左上隅の座標をリセットすることです。
2.3 簡単なツール
package cn.chendd.core.utils.zxing;
/**
* 二维码生成工具类
*
* @author chendd
* @date 2014/06/06 10:20
*/
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.ImageReader;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.compress.utils.CharsetNames;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class BarCodeUtil {
/**
* <pre>
*
* 对已存在的文件地址进行解码,Copy to 下载的源码中的例子
*
* </pre>
*
* @param file 文件路径
* @return 解码后的字符串
* @author chendd, 2014-6-6 上午11:03:01
*/
private static String getDecodeText(Path file) {
BufferedImage image;
try {
image = ImageReader.readImage(file.toUri());
} catch (IOException ioe) {
return ioe.toString();
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
try {
result = new MultiFormatReader().decode(bitmap);
} catch (ReaderException re) {
re.printStackTrace();
return re.toString();
}
return String.valueOf(result.getText());
}
/**
* <pre>
*
* 根据文件路径和类型(条形码/二维码等)写入相关文件
*
* </pre>
*
* @param contents 写入类型
* @param type 写入的图片类型,如二维码、条形码等等
* @param format 图片格式
* @param width 图片宽度
* @param height 图片高度
* @param writeFile 写入文件
* @throws Exception 抛出异常的爱
* @author chendd, 2014-6-6 下午3:50:39
*/
public static void writeToFile(String contents, BarcodeFormat type,
String format, int width, int height, File writeFile)
throws Exception {
BitMatrix matrix = new MultiFormatWriter().encode(contents, type, width, height);
MatrixToImageWriter.writeToPath(matrix, format, writeFile.toPath());
}
public static void writeToStream(String contents, BarcodeFormat type,
String format, int width, int height, OutputStream os)
throws Exception {
Map<EncodeHintType, Object> mapConfig = new HashMap<EncodeHintType, Object>();
// 用于设置QR二维码参数
// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
mapConfig.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 设置编码方式
mapConfig.put(EncodeHintType.CHARACTER_SET, CharsetNames.UTF_8);
mapConfig.put(EncodeHintType.MARGIN, 0);
BitMatrix matrix = new MultiFormatWriter().encode(contents, type, width, height , mapConfig);
MatrixToImageWriter.writeToStream(matrix, format, os);
}
/**
* 定制二维码输出
* @param content 内容
* @param os 输出流
* @throws Exception 异常处理
*/
public static void writeToStream(String content , OutputStream os) throws Exception {
BarCodeUtil.writeToStream(content, BarcodeFormat.QR_CODE, "png", 200, 200, os);
}
}
3. テスト検証
PS: 白いマージンはありませんが、出力される画像のサイズは実際に設定された画像サイズより一回り小さいですが、今のところ大きな問題はないようです。
【その他注意事項】
さらに個人的な経験の共有は、個人のブログ サイトに転送できます: https://www.chendd.cn
ウェブサイト記事アドレス: https://www.chendd.cn/blog/article/1633047307104395266.html