使用Zxing生成DM码不是正方形的问题
在hints中增加
hints.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE);//设置样式:不设置,正方形,矩形
SymbolShapeHint.FORCE_NONE 默认
SymbolShapeHint.FORCE_SQUARE 正方形
SymbolShapeHint.FORCE_RECTANGLE 矩形
/**
* @param content 二维码内容
* @param width 二维码宽度
* @param height 二维码高度
* @param charset 字符编码
* @param barcodeFormat 二维码类型QR、DM、条形码
* @param errorCorrectionLevel 容错级别
* @param margin 边距
* @param color 二维码颜色 16进制 例如:#ff000000
* @param colorBg 背景色 16进制 例如:#ffffffff
* @return
*/
public static Bitmap createImage(String content, int width, int height, String charset,
BarcodeFormat barcodeFormat,
ErrorCorrectionLevel errorCorrectionLevel,
int margin, int color, int colorBg) {
try {
//判断URL合法性
if (content == null || "".equals(content) || content.length() < 1) {
return null;
}
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, charset);//编码格式
hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel);//容错类型
hints.put(EncodeHintType.MARGIN, margin);//边距
hints.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE);//设置样式:不设置,正方形,矩形
//图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, barcodeFormat, width, height, hints);
int[] pixels = new int[width * height];
//下面这里按照二维码的算法,逐个生成二维码的图片,
//两个for循环是图片横列扫描的结果
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = color;
} else {
pixels[y * height + x] = colorBg;
}
}
}
//生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
调用方法
createImage(content, width, height, "utf-8",
BarcodeFormat.DATA_MATRIX, errorCorrectionLevel, margin, 0XFF000000, 0XFFFFFFFF);