如何去除二维码的空白区域

 

// 创建二维码位图
    public static BufferedImage createQrImg(String content, Integer width, Integer height) throws Exception
    {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 生成矩阵信息
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        // 遍历矩阵,获取矩阵中黑点开始的位置
        int matrixWidth = bitMatrix.getWidth();
        int matrixHeight = bitMatrix.getHeight();
        Integer startX = null;
        Integer startY = null;
        for (int x = 0; x < matrixWidth; x++)
        {
            if(null!=startX){
                break;
            }
            for (int y = 0; y < matrixHeight; y++)
            {
                if (bitMatrix.get(x, y))
                {
                    // 如果有黑点,临时记录下来
                    startX = x;
                    startY = y;
                    break;
                }
            }
        }
        // 将矩阵信息转为图片信息(宽 和 高 要减去 两边 空白区的长度)
        BufferedImage image = new BufferedImage(width-2*startX, height-2*startY, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLACK);
        for (int x = startX; x < matrixWidth-startX; x++)
        {
            for (int y = startY; y < matrixHeight-startY; y++)
            {
                if (bitMatrix.get(x, y))
                {
                    // 如果有黑点,则画到图上去(从图上的0点开始画起)
                    graphics.fillRect(x-startX , y-startY, 1, 1);
                }
            }
        }
        image.flush();
        return image;
    }

 

你可能感兴趣的:(javaee)