[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[转帖]Zxing工具类,生成二维码并去掉白色边框

上一篇:[备忘]java解析简单的数学表达式。
下一篇:[备忘]tomcat的keepAlive设置(keepAliveTimeout和maxKeepAliveRequests)

添加日期:2022/9/29 20:19:15 快速返回   返回列表 阅读345次


/**
 * Author: 侯亚东
 * Date: 2022-01-20 15:10
 * Email: houyadong1@gome.com.cn
 * Des: 二维码生成工具类
 */
public class ZxingUtils {

    /**
     * 生成二维码Bitmap
     *
     * @param content       内容
     * @param widthPix      图片宽度
     * @param heightPix     图片高度
     * @param isDeleteWhite 是否删除白色边框
     * @return 生成的二维码Bitmap
     */
    public static Bitmap createQRImage(String content, int widthPix, int heightPix, boolean isDeleteWhite) {
        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, isDeleteWhite ? 1 : 0);
            BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            if (isDeleteWhite) {
                //删除白边
                matrix = deleteWhite(matrix);
            }
            widthPix = matrix.getWidth();
            heightPix = matrix.getHeight();
            int[] pixels = new int[widthPix * heightPix];
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * widthPix + x] = Color.BLACK;
                    } else {
                        pixels[y * widthPix + x] = Color.WHITE;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 删除白色边框
     *
     * @param matrix matrix
     * @return BitMatrix
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle(); //这句是重点吧
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }
}

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved