Zxin包生成二維碼白邊問題解決方法

package com;


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.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;
import java.util.Map;

/***/
public final class QRCodeWriter implements Writer {
private static final int QUIET_ZONE_SIZE = 4;


public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException {
return encode(contents, format, width, height, null);
}
/**
* 需要白邊請調用該方法
* @param contents
* @param format
* @param width 寬度
* @param height 高度
* @param quietZone 白邊大小
* @param hints
* @return
* @throws WriterException
*/
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height,int quietZone, 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;

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


/**
* 無需白邊,調用此方法
* @param contents
* @param format
* @param width
* @param height
* @param hints
* @return
* @throws WriterException
*/
public BitMatrix encodeNo(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;

if (hints != null) {
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
errorCorrectionLevel = ErrorCorrectionLevel
.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}

}


QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);
return renderResult(code, width, height);
}

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


int leftPadding = (outputWidth - inputWidth * multiple) / 2;
int topPadding = (outputHeight - inputHeight * multiple) / 2;


BitMatrix output = new BitMatrix(outputWidth, outputHeight);


int inputY = 0;
for (int outputY = topPadding; inputY < inputHeight; outputY += multiple) {
int inputX = 0;
for (int outputX = leftPadding; inputX < inputWidth; outputX += multiple) {
if (input.get(inputX, inputY) == 1)
output.setRegion(outputX, outputY, multiple, multiple);
inputX++;
}
inputY++;
}


return output;
}
/**
* 去除二維碼白邊
*/
private static BitMatrix renderResult(QRCode code, int width, int height) {
        ByteMatrix input = code.getMatrix();
        if (input == null) {
            throw new IllegalStateException();
        }
        int inputWidth = input.getWidth();
        int inputHeight = input.getHeight();
        // 依據用戶的輸入寬高,計算白邊後的輸出寬高
        int outputWidth = Math.max(width, inputWidth);
        int outputHeight = Math.max(height, inputHeight);


  //計算縮放比例
        int multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight);


   BitMatrix output = new BitMatrix(outputWidth, outputHeight);
        int inputY = 0;
        // 嵌套循環,將ByteMatrix的內容計算padding後轉換成BitMatrix
        for (int outputY = 0; inputY < inputHeight; outputY += multiple) {
            int inputX = 0;
            for (int outputX = 0; inputX < inputWidth; outputX += multiple) {
                if (input.get(inputX, inputY) == 1) {
                    output.setRegion(outputX, outputY, multiple, multiple);
                }
                inputX++;
            }
            inputY++;
        }


   return output;
}


@Override
public BitMatrix encode(String arg0, BarcodeFormat arg1, int arg2, int arg3, Map<EncodeHintType, ?> arg4)
throws WriterException {
// TODO Auto-generated method stub
return null;
}

}

/****************************************以下爲測試類,請自行下載Zxing的jar包**************************************************************/

package com;


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Random;


import javax.imageio.ImageIO;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;


public class TestQrCode {


public static String createQrcode(String _text) {
String qrcodeFilePath = "";
try {
int qrcodeWidth = 300;
int qrcodeHeight = 300;
int quietZone = 4;// 設置白邊寬度,如果不需要白邊請調用encodeNo方法encode(_text,BarcodeFormat.QR_CODE, qrcodeWidth,qrcodeHeight, hints);
String qrcodeFormat = "png";
HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
QRCodeWriter q = new QRCodeWriter();
BitMatrix bitMatrix = q.encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, quietZone, hints);


BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
Random random = new Random();

File QrcodeFile = new File("F:\\qrcode\\" + random.nextInt() + "." + qrcodeFormat);
ImageIO.write(image, qrcodeFormat, QrcodeFile);
MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile);

qrcodeFilePath = QrcodeFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return qrcodeFilePath;
}


public static void main(String[] args) {
String path = TestQrCode.createQrcode("gsdw—2017");
File f = new File(path);
new TestQrCode().addtext_QRCode(f,"");
//System.out.println(path);
//System.out.println(System.getProperty("os.name"));
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章