下面列出了怎么用com.google.zxing.common.BitMatrix的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*二维码实现
* @param msg /二维码包含的信息
* @param path /二维码存放路径
*/
public static void getBarCode(String msg,String path){
try {
File file=new File(path);
OutputStream ous=new FileOutputStream(file);
if(StringUtils.isEmpty(msg) || ous==null)
return;
String format = "png";
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType,String> map =new HashMap<EncodeHintType, String>();
//设置编码 EncodeHintType类中可以设置MAX_SIZE, ERROR_CORRECTION,CHARACTER_SET,DATA_MATRIX_SHAPE,AZTEC_LAYERS等参数
map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
map.put(EncodeHintType.MARGIN,"1");
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE,300,300,map);
MatrixToImageWriter.writeToStream(bitMatrix,format,ous);
}catch (Exception e) {
e.printStackTrace();
}
}
public static Bitmap getQrCodeImage(String data, int width, int height) {
if (data == null || data.length() == 0) {
return null;
}
Map<EncodeHintType, Object> hintsMap = new HashMap<>(3);
hintsMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
hintsMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hintsMap.put(EncodeHintType.MARGIN, 0);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hintsMap);
Bitmap bitmap = bitMatrix2Bitmap(bitMatrix);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* Encode the contents following specified format.
* {@code width} and {@code height} are required size. This method may return bigger size
* {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
* {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
* or {@code height}, {@code IllegalArgumentException} is thrown.
*/
@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 (width < 0 || height < 0) {
throw new IllegalArgumentException("Negative size is not allowed. Input: "
+ width + 'x' + height);
}
int sidesMargin = getDefaultMargin();
if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
boolean[] code = encode(contents);
return renderResult(code, width, height, sidesMargin);
}
/**
* Locate the vertices and the codewords area of a black blob using the Start
* and Stop patterns as locators.
*
* @param matrix the scanned barcode image.
* @return an array containing the vertices:
* vertices[0] x, y top left barcode
* vertices[1] x, y bottom left barcode
* vertices[2] x, y top right barcode
* vertices[3] x, y bottom right barcode
* vertices[4] x, y top left codeword area
* vertices[5] x, y bottom left codeword area
* vertices[6] x, y top right codeword area
* vertices[7] x, y bottom right codeword area
*/
private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) {
int height = matrix.getHeight();
int width = matrix.getWidth();
ResultPoint[] result = new ResultPoint[8];
copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN),
INDEXES_START_PATTERN);
if (result[4] != null) {
startColumn = (int) result[4].getX();
startRow = (int) result[4].getY();
}
copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN),
INDEXES_STOP_PATTERN);
return result;
}
public Bitmap generateQRCode(String text) {
Bitmap bmp = null;
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage
int size = 256;
BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hintMap);
int width = bitMatrix.getWidth();
bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
bmp.setPixel(y, x, bitMatrix.get(x, y) == true ? Color.BLACK : Color.WHITE);
}
}
} catch (WriterException e) {
e.printStackTrace();
}
return bmp;
}
public static Bitmap generateBitmap(String content, int width, int height) {
int margin = 5; //自定义白边边框宽度
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Hashtable hints = new Hashtable<>();
hints.put(EncodeHintType.MARGIN, 0);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// encode = updateBit(encode, margin); //生成新的bitMatrix
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* Locate the vertices and the codewords area of a black blob using the Start
* and Stop patterns as locators.
*
* @param matrix the scanned barcode image.
* @return an array containing the vertices:
* vertices[0] x, y top left barcode
* vertices[1] x, y bottom left barcode
* vertices[2] x, y top right barcode
* vertices[3] x, y bottom right barcode
* vertices[4] x, y top left codeword area
* vertices[5] x, y bottom left codeword area
* vertices[6] x, y top right codeword area
* vertices[7] x, y bottom right codeword area
*/
private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) {
int height = matrix.getHeight();
int width = matrix.getWidth();
ResultPoint[] result = new ResultPoint[8];
copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN),
INDEXES_START_PATTERN);
if (result[4] != null) {
startColumn = (int) result[4].getX();
startRow = (int) result[4].getY();
}
copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN),
INDEXES_STOP_PATTERN);
return result;
}
private Bitmap createQRImage(String address) {
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int imageSize = (int) (size.x * QR_IMAGE_WIDTH_RATIO);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(
address,
BarcodeFormat.QR_CODE,
imageSize,
imageSize,
null);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
return barcodeEncoder.createBitmap(bitMatrix);
} catch (Exception e) {
Toast.makeText(this, getString(R.string.error_fail_generate_qr), Toast.LENGTH_SHORT)
.show();
}
return null;
}
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* Locate the vertices and the codewords area of a black blob using the Start
* and Stop patterns as locators.
*
* @param matrix the scanned barcode image.
* @return an array containing the vertices:
* vertices[0] x, y top left barcode
* vertices[1] x, y bottom left barcode
* vertices[2] x, y top right barcode
* vertices[3] x, y bottom right barcode
* vertices[4] x, y top left codeword area
* vertices[5] x, y bottom left codeword area
* vertices[6] x, y top right codeword area
* vertices[7] x, y bottom right codeword area
*/
private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) {
int height = matrix.getHeight();
int width = matrix.getWidth();
ResultPoint[] result = new ResultPoint[8];
copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN),
INDEXES_START_PATTERN);
if (result[4] != null) {
startColumn = (int) result[4].getX();
startRow = (int) result[4].getY();
}
copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN),
INDEXES_STOP_PATTERN);
return result;
}
/**
* 同步创建指定前景色、指定背景色二维码图片
* <pre>
* 该方法是耗时操作, 请在子线程中调用
* </pre>
* @param content 生成内容
* @param size 图片宽高大小 ( 正方形 px )
* @param foregroundColor 二维码图片的前景色
* @param backgroundColor 二维码图片的背景色
* @return 二维码图片
*/
public static Bitmap syncEncodeQRCode(final String content, final int size, final int foregroundColor, final int backgroundColor) {
try {
BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, ENCODE_HINTS);
int[] pixels = new int[size * size];
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
if (matrix.get(x, y)) {
pixels[y * size + x] = foregroundColor;
} else {
pixels[y * size + x] = backgroundColor;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
return bitmap;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "syncEncodeQRCode");
return null;
}
}
public WhiteRectangleDetector(BitMatrix bitmatrix)
{
c = bitmatrix;
d = bitmatrix.getHeight();
e = bitmatrix.getWidth();
f = -30 + e >> 1;
g = 30 + e >> 1;
i = -30 + d >> 1;
h = 30 + d >> 1;
if (i < 0 || f < 0 || h >= d || g >= e)
{
throw NotFoundException.getNotFoundInstance();
} else
{
return;
}
}
/**
* Encode the contents following specified format.
* {@code width} and {@code height} are required size. This method may return bigger size
* {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
* {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
* or {@code height}, {@code IllegalArgumentException} is thrown.
*/
@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 (width < 0 || height < 0) {
throw new IllegalArgumentException("Negative size is not allowed. Input: "
+ width + 'x' + height);
}
int sidesMargin = getDefaultMargin();
if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
boolean[] code = encode(contents);
return renderResult(code, width, height, sidesMargin);
}
public static Bitmap generateBitmap(String content, int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
private static int adjustCodewordStartColumn(BitMatrix image,
int minColumn,
int maxColumn,
boolean leftToRight,
int codewordStartColumn,
int imageRow) {
int correctedStartColumn = codewordStartColumn;
int increment = leftToRight ? -1 : 1;
// there should be no black pixels before the start column. If there are, then we need to start earlier.
for (int i = 0; i < 2; i++) {
while (((leftToRight && correctedStartColumn >= minColumn) || (!leftToRight && correctedStartColumn < maxColumn)) &&
leftToRight == image.get(correctedStartColumn, imageRow)) {
if (Math.abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE) {
return codewordStartColumn;
}
correctedStartColumn += increment;
}
increment = -increment;
leftToRight = !leftToRight;
}
return correctedStartColumn;
}
public static Bitmap create2dBarcodeBitmap(String input, int size) {
try {
final QRCodeWriter barcodeWriter = new QRCodeWriter();
final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
final BitMatrix result = barcodeWriter.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
final int width = result.getWidth();
final int height = result.getHeight();
final int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
final int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
}
}
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
public static BitMatrix genRQCode(String rqCodeText,int width, int height ){
if(width==0){
width=200;
}
if(height==0){
height=200;
}
try {
return new MultiFormatWriter().encode(
rqCodeText,
BarcodeFormat.QR_CODE,
width,
height);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Creates a BitMatrix by sampling the provided image.
* topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
* diagonal just outside the bull's eye.
*/
private BitMatrix sampleGrid(BitMatrix image,
ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomRight,
ResultPoint bottomLeft) throws NotFoundException {
GridSampler sampler = GridSampler.getInstance();
int dimension = getDimension();
float low = dimension / 2.0f - nbCenterLayers;
float high = dimension / 2.0f + nbCenterLayers;
return sampler.sampleGrid(image,
dimension,
dimension,
low, low, // topleft
high, low, // topright
high, high, // bottomright
low, high, // bottomleft
topLeft.getX(), topLeft.getY(),
topRight.getX(), topRight.getY(),
bottomRight.getX(), bottomRight.getY(),
bottomLeft.getX(), bottomLeft.getY());
}
/**
* <p>Extracts the data region from a {@link BitMatrix} that contains
* alignment patterns.</p>
*
* @param bitMatrix Original {@link BitMatrix} with alignment patterns
* @return BitMatrix that has the alignment patterns removed
*/
BitMatrix extractDataRegion(BitMatrix bitMatrix) {
int symbolSizeRows = version.getSymbolSizeRows();
int symbolSizeColumns = version.getSymbolSizeColumns();
if (bitMatrix.getHeight() != symbolSizeRows) {
throw new IllegalArgumentException("Dimension of bitMarix must match the version size");
}
int dataRegionSizeRows = version.getDataRegionSizeRows();
int dataRegionSizeColumns = version.getDataRegionSizeColumns();
int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows;
int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns;
int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);
for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) {
int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
for (int i = 0; i < dataRegionSizeRows; ++i) {
int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
int writeRowOffset = dataRegionRowOffset + i;
for (int j = 0; j < dataRegionSizeColumns; ++j) {
int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
if (bitMatrix.get(readColumnOffset, readRowOffset)) {
int writeColumnOffset = dataRegionColumnOffset + j;
bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset);
}
}
}
}
}
return bitMatrixWithoutAlignment;
}
/**
* 活动二维码下载 (通用方法)
* @param url :二维码网址
*/
@RequestMapping(value = "downMatrix", method ={RequestMethod.GET,RequestMethod.POST})
public void downMatrix(@RequestParam(required = true, value = "qrCodeName") String qrCodeName,@RequestParam(required = true, value = "url") String url, HttpServletResponse response, HttpServletRequest request) throws Exception {
String text = url;
int width = 500; // 二维码图片宽度
int height = 500; // 二维码图片高度
String format = "jpg";// 二维码的图片格式
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, width, height, hints);
// 获取文件名
String fileName = "";
if(qrCodeName!=null)
{
fileName = qrCodeName+".jpg";
}else{
fileName = "活动二维码.jpg";
}
// 制定浏览器头
// 在下载的时候这里是英文是没有问题的
// 如果图片名称是中文需要设置转码
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream out = response.getOutputStream();;
try {
// 读取文件
MatrixToImageWriter.writeToStream(bitMatrix, format, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
public DecoderResult decode(AztecDetectorResult detectorResult) throws FormatException {
ddata = detectorResult;
BitMatrix matrix = detectorResult.getBits();
boolean[] rawbits = extractBits(matrix);
boolean[] correctedBits = correctBits(rawbits);
byte[] rawBytes = convertBoolArrayToByteArray(correctedBits);
String result = getEncodedData(correctedBits);
DecoderResult decoderResult = new DecoderResult(rawBytes, result, null, null);
decoderResult.setNumBits(correctedBits.length);
return decoderResult;
}
ActionResult<Wo> execute(EffectivePerson effectivePerson) throws Exception {
//Audit audit = logger.audit(effectivePerson);
ActionResult<Wo> result = new ActionResult<>();
Wo wo = new Wo();
String meta = StringTools.uniqueToken();
/** 二维码内容 */
String url = UriBuilder.fromUri(Config.collect().getAppUrl()).queryParam("meta", meta).build().toASCIIString();
int width = 200; // 二维码图片宽度
int height = 200; // 二维码图片高度
String format = "png";// 二维码的图片格式
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
// hints.put(EncodeHintType.CHARACTER_SET, DefaultCharset.name); //
// 内容所使用字符集编码
hints.put(EncodeHintType.MARGIN, "1");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q.toString());
// hints.put(EncodeHintType.QR_VERSION, "7");
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
}
}
Graphics2D graphics = image.createGraphics();
Image logo = ImageIO.read(new ByteArrayInputStream(Config.bindLogo()));
graphics.drawImage(logo, 68, 68, null);
graphics.dispose();
logo.flush();
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
ImageIO.write(image, format, out);
wo.setImage(Base64.encodeBase64String(out.toByteArray()));
}
wo.setMeta(meta);
result.setData(wo);
return result;
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height) throws WriterException {
return encode(contents, format, width, height, null);
}
BoundingBox(BitMatrix image,
ResultPoint topLeft,
ResultPoint bottomLeft,
ResultPoint topRight,
ResultPoint bottomRight) throws NotFoundException {
if ((topLeft == null && topRight == null) ||
(bottomLeft == null && bottomRight == null) ||
(topLeft != null && bottomLeft == null) ||
(topRight != null && bottomRight == null)) {
throw NotFoundException.getNotFoundInstance();
}
init(image, topLeft, bottomLeft, topRight, bottomRight);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) throws WriterException {
if (format != BarcodeFormat.CODE_128) {
throw new IllegalArgumentException("Can only encode CODE_128, but got " + format);
}
return super.encode(contents, format, width, height, hints);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
Map<EncodeHintType,?> hints) throws WriterException {
if (format != BarcodeFormat.UPC_A) {
throw new IllegalArgumentException("Can only encode UPC-A, but got " + format);
}
return subWriter.encode(preencode(contents), BarcodeFormat.EAN_13, width, height, hints);
}
/**
* As {@link #writeToFile(BitMatrix, String, File)}, but allows customization of the output.
*/
public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, file.toFile())) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
/**
* As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output.
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static byte[] getZXingQRCode(String data, int size){
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, size, size, hints);
System.out.println("bitmatrix height:" + bitMatrix.getHeight() + " width:" + bitMatrix.getWidth());
return getBytesFromBitMatrix(bitMatrix);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}