public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException { Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight); int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = BLACK; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
/**显示二维码 */ protected void setQRCode() { runThread(TAG + "setQRCode", new Runnable() { @Override public void run() { try { qRCodeBitmap = EncodingHandler.createQRCode(Constant.APP_DOWNLOAD_WEBSITE , (int) (2 * getResources().getDimension(R.dimen.qrcode_size))); } catch (WriterException e) { e.printStackTrace(); Log.e(TAG, "initData try {Bitmap qrcode = EncodingHandler.createQRCode(contactJson, ivContactQRCodeCode.getWidth());" + " >> } catch (WriterException e) {" + e.getMessage()); } runUiThread(new Runnable() { @Override public void run() { ivAboutQRCode.setImageBitmap(qRCodeBitmap); } }); } }); }
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException { if (contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } else if (format != BarcodeFormat.QR_CODE) { throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } else if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } else { ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; int quietZone = 4; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } Integer quietZoneInt = (Integer) hints.get(EncodeHintType.MARGIN); if (quietZoneInt != null) { quietZone = quietZoneInt.intValue(); } } return renderResult(Encoder.encode(contents, errorCorrectionLevel, hints), width, height, quietZone); } }
private void encodeFromTextExtras(Intent intent) throws WriterException { // Notice: Google Maps shares both URL and details in one text, bummer! String theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_TEXT)); if (theContents == null) { theContents = ContactEncoder.trim(intent.getStringExtra("android.intent.extra.HTML_TEXT")); // Intent.EXTRA_HTML_TEXT if (theContents == null) { theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_SUBJECT)); if (theContents == null) { String[] emails = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); if (emails != null) { theContents = ContactEncoder.trim(emails[0]); } else { theContents = "?"; } } } } // Trim text to avoid URL breaking. if (theContents == null || theContents.isEmpty()) { throw new WriterException("Empty EXTRA_TEXT"); } contents = theContents; // We only do QR code. format = BarcodeFormat.QR_CODE; if (intent.hasExtra(Intent.EXTRA_SUBJECT)) { displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT); } else if (intent.hasExtra(Intent.EXTRA_TITLE)) { displayContents = intent.getStringExtra(Intent.EXTRA_TITLE); } else { displayContents = contents; } title = activity.getString(R.string.contents_text); }
private void updateQrCode(String qrData) { DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // the results will be higher than using the activity context object or the getWindowManager() shortcut wm.getDefaultDisplay().getMetrics(displayMetrics); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; int qrCodeDimension = screenWidth > screenHeight ? screenHeight : screenWidth; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimension); try { mBitmap = qrCodeEncoder.encodeAsBitmap(); mImageView.setImageBitmap(mBitmap); mImageView.setVisibility(View.VISIBLE); mErrorView.setVisibility(View.GONE); } catch (WriterException e) { e.printStackTrace(); mErrorView.setText("Error: "+e.getMessage()); mErrorView.setVisibility(View.VISIBLE); mImageView.setVisibility(View.GONE); } }
public Bitmap encodeAsBitmap() throws WriterException { if (!encoded) return null; Map<EncodeHintType, Object> hints = null; String encoding = guessAppropriateEncoding(contents); if (encoding != null) { hints = new EnumMap<>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, encoding); } MultiFormatWriter writer = new MultiFormatWriter(); BitMatrix result = writer.encode(contents, format, dimension, dimension, hints); int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; // All are 0, or black, by default for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException { Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight); int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = BLACK; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
private Bitmap createQRCode(String str, int widthAndHeight) throws WriterException { Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 使用utf8编码 BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);// 这里需要把hints传进去,否则会出现中文乱码 int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; // 上色,如果不做保存二维码、分享二维码等功能,上白色部分可以不写。至于原因,在生成图片的时候,如果没有指定颜色,其会使用系统默认颜色来上色,很多情况就会出现保存的二维码图片全黑 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) {// 有数据的像素点使用黑色 pixels[y * width + x] = BLACK; } else {// 其他部分则使用白色 pixels[y * width + x] = WHITE; } } } //生成bitmap Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
public static @NonNull Bitmap create(String data) { try { BitMatrix result = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, 512, 512); Bitmap bitmap = Bitmap.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888); for (int y = 0; y < result.getHeight(); y++) { for (int x = 0; x < result.getWidth(); x++) { if (result.get(x, y)) { bitmap.setPixel(x, y, Color.BLACK); } } } return bitmap; } catch (WriterException e) { Log.w(TAG, e); return Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888); } }
/** * 关于Ansi Color的信息,参考:http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html * * @param text */ public static void printQRCodeInTerminal(String text) { int qrcodeWidth = 400; int qrcodeHeight = 400; HashMap<EncodeHintType, String> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); try { BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints); // 将像素点转成格子 int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); for (int y = 30; y < height - 30; y += 10) { for (int x = 30; x < width - 20; x += 10) { boolean isBlack = bitMatrix.get(x, y); System.out.print(isBlack ? " " : "\u001b[47m \u001b[0m"); } System.out.println(); } } catch (WriterException e) { e.printStackTrace(); } }
static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitArray maskBits = new BitArray(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.getSize() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.getSize()); } }
@Nullable static Bitmap createQrCode(DisplayMetrics dm, String input) { int smallestDimen = Math.min(dm.widthPixels, dm.heightPixels); try { // Generate QR code final BitMatrix encoded = new QRCodeWriter().encode( input, QR_CODE, smallestDimen, smallestDimen); // Convert QR code to Bitmap int width = encoded.getWidth(); int height = encoded.getHeight(); int[] pixels = new int[width * height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { pixels[y * width + x] = encoded.get(x, y) ? BLACK : WHITE; } } Bitmap qr = Bitmap.createBitmap(width, height, ARGB_8888); qr.setPixels(pixels, 0, width, 0, 0, width, height); return qr; } catch (WriterException e) { if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e); return null; } }
static void appendKanjiBytes(String content, BitArray bits) throws WriterException { try { byte[] bytes = content.getBytes("Shift_JIS"); int length = bytes.length; for (int i = 0; i < length; i += 2) { int byte2 = bytes[i + 1] & 255; int code = ((bytes[i] & 255) << 8) | byte2; int subtracted = -1; if (code >= 33088 && code <= 40956) { subtracted = code - 33088; } else if (code >= 57408 && code <= 60351) { subtracted = code - 49472; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } bits.appendBits(((subtracted >> 8) * 192) + (subtracted & 255), 13); } } catch (UnsupportedEncodingException uee) { throw new WriterException(uee); } }
static void appendKanjiBytes(String content, BitArray bits) throws WriterException { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee); } int length = bytes.length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } }
public static String getQr(String text) { String s = "生成二维码失败"; int width = 40; int height = 40; // 用于设置QR二维码参数 Hashtable<EncodeHintType, Object> qrParam = new Hashtable<EncodeHintType, Object>(); // 设置QR二维码的纠错级别——这里选择最低L级别 qrParam.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); qrParam.put(EncodeHintType.CHARACTER_SET, "utf-8"); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, qrParam); s = toAscii(bitMatrix); } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; }
static void terminateBits(int numDataBytes, BitArray bits) throws WriterException { int capacity = numDataBytes * 8; if (bits.getSize() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.getSize() + " " + "> " + capacity); } int i; for (i = 0; i < 4 && bits.getSize() < capacity; i++) { bits.appendBit(false); } int numBitsInLastByte = bits.getSize() & 7; if (numBitsInLastByte > 0) { for (i = numBitsInLastByte; i < 8; i++) { bits.appendBit(false); } } int numPaddingBytes = numDataBytes - bits.getSizeInBytes(); for (i = 0; i < numPaddingBytes; i++) { bits.appendBits((i & 1) == 0 ? 236 : 17, 8); } if (bits.getSize() != capacity) { throw new WriterException("Bits size does not equal capacity"); } }
/** * 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); }
private static int chooseMaskPattern(BitArray bits, ErrorCorrectionLevel ecLevel, Version version, ByteMatrix matrix) throws WriterException { int minPenalty = Integer.MAX_VALUE; // Lower penalty is better. int bestMaskPattern = -1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; }
public static BufferedImage createQRCode(String qrCodeData, String charset, Map hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException { //Create the BitMatrix representing the QR code BitMatrix matrix = new MultiFormatWriter().encode( new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap); //Create BufferedImages from the QRCode BitMatricies return MatrixToImageWriter.toBufferedImage(matrix); }
/** * 比方法2的颜色黑一些 * * @param text * @param size * @param mBitmap * @return */ public static Bitmap createQRCodeWithLogo4(String text, int size, Bitmap mBitmap) { try { IMAGE_HALFWIDTH = size / 10; Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hints); //将logo图片按martix设置的信息缩放 mBitmap = Bitmap.createScaledBitmap(mBitmap, size, size, false); int[] pixels = new int[size * size]; boolean flag = true; for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { if (bitMatrix.get(x, y)) { if (flag) { flag = false; pixels[y * size + x] = 0xff000000; } else { pixels[y * size + x] = mBitmap.getPixel(x, y); flag = true; } } else { pixels[y * size + x] = 0xffffffff; } } } Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, size, 0, 0, size, size); return bitmap; } catch (WriterException e) { e.printStackTrace(); return null; } }
static void append8BitBytes(String content, BitArray bits, String encoding) throws WriterException { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee); } for (byte b : bytes) { bits.appendBits(b, 8); } }
public void generateBarcodeLogic(String msg, int errorCorrectionLevel) throws WriterException { int errorCorrectionCodeWords = PDF417ErrorCorrection.getErrorCorrectionCodewordCount (errorCorrectionLevel); String highLevel = PDF417HighLevelEncoder.encodeHighLevel(msg, this.compaction, this .encoding); int sourceCodeWords = highLevel.length(); int[] dimension = determineDimensions(sourceCodeWords, errorCorrectionCodeWords); int cols = dimension[0]; int rows = dimension[1]; int pad = getNumberOfPadCodewords(sourceCodeWords, errorCorrectionCodeWords, cols, rows); if ((sourceCodeWords + errorCorrectionCodeWords) + 1 > PDF417Common.NUMBER_OF_CODEWORDS) { throw new WriterException("Encoded message contains to many code words, message to " + "big (" + msg.length() + " bytes)"); } int n = (sourceCodeWords + pad) + 1; StringBuilder stringBuilder = new StringBuilder(n); stringBuilder.append((char) n); stringBuilder.append(highLevel); for (int i = 0; i < pad; i++) { stringBuilder.append('΄'); } String dataCodewords = stringBuilder.toString(); String fullCodewords = dataCodewords + PDF417ErrorCorrection.generateErrorCorrection (dataCodewords, errorCorrectionLevel); this.barcodeMatrix = new BarcodeMatrix(rows, cols); encodeLowLevel(fullCodewords, cols, rows, errorCorrectionLevel, this.barcodeMatrix); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_share); QRImage = (ImageView)findViewById(R.id.QRCode); buttonGenerate = (Button)findViewById(R.id.button_generate); buttonGenerate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { QRCodeWriter writer = new QRCodeWriter(); hackmelockDevice = dbHelper.getConfig(); String toEncode = utils.majorMinorToHexString(hackmelockDevice.Major, hackmelockDevice.Minor) + ":" + utils.bytesToHex(hackmelockDevice.keys[KeyID]) + ":" + KeyID +":" + System.currentTimeMillis()/1000 + ":" + DateTo; Log.d("Share","Text to encode: " + toEncode); //contains sensitive information (key) try { BitMatrix bitMatrix = writer.encode(toEncode, BarcodeFormat.QR_CODE, 256, 256); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE); } } QRImage.setImageBitmap(bmp); QRImage.setVisibility(View.VISIBLE); buttonGenerate.setVisibility(View.VISIBLE); } catch (WriterException e) { e.printStackTrace(); } } }); }
/** * 创建二维码 * * @param content content * @param widthPix widthPix * @param heightPix heightPix * @param logoBm logoBm * @return 二维码 */ public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) { try { if (content == null || "".equals(content)) { return null; } // 配置参数 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 容错级别 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints); int[] pixels = new int[widthPix * heightPix]; // 下面这里按照二维码的算法,逐个生成二维码的图片, // 两个for循环是图片横列扫描的结果 for (int y = 0; y < heightPix; y++) { for (int x = 0; x < widthPix; x++) { if (bitMatrix.get(x, y)) { pixels[y * widthPix + x] = 0xff000000; } else { pixels[y * widthPix + x] = 0xffffffff; } } } // 生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix); if (logoBm != null) { bitmap = addLogo(bitmap, logoBm); } //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大! return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); } vcard = baos.toByteArray(); vcardString = new String(vcard, 0, vcard.length, "UTF-8"); } catch (IOException ioe) { throw new WriterException(ioe); } Log.d(TAG, "Encoding share intent content:"); Log.d(TAG, vcardString); Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.isEmpty()) { throw new WriterException("No content to encode"); } }
@Test public void createQRFromBedURLTest() throws IOException, WriterException, NotFoundException { BufferedImage qr = QRCodes.createQRFromURL("http://dorfner.congrue.xyz:2538/bed/1N"); BufferedImage qr2 = QRCodes.createQRFromURL("http://dorfner.congrue.xyz:2538/bed/2S"); assertEquals("The 1N bed QR code has an incorrect URL", "http://dorfner.congrue.xyz:2538/bed/1N", readQRCode(qr, hintMap)); assertEquals("The 2S bed QR code has an incorrect URL", "http://dorfner.congrue.xyz:2538/bed/2S", readQRCode(qr2, hintMap)); }
Bitmap encodeAsBitmap() throws WriterException { String contentsToEncode = contents; if (contentsToEncode == null) { return null; } Map<EncodeHintType,Object> hints = null; String encoding = guessAppropriateEncoding(contentsToEncode); if (encoding != null) { hints = new EnumMap<>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, encoding); } BitMatrix result; try { result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints); } catch (IllegalArgumentException iae) { // Unsupported format return null; } int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }
@Override protected Bitmap doInBackground(Void... params) { BarcodeGenerator generator = new BarcodeGenerator(context); try { return generator.renderBarcode(card.getBarcode(), card.getFormat(), 300, 50); } catch (WriterException e) { exception = e; } return null; }
private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { // Embed three big squares at corners. int pdpWidth = POSITION_DETECTION_PATTERN[0].length; // Left top corner. embedPositionDetectionPattern(0, 0, matrix); // Right top corner. embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); // Left bottom corner. embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); // Embed horizontal separation patterns around the squares. int hspWidth = 8; // Left top corner. embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); // Right top corner. embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix); // Left bottom corner. embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix); // Embed vertical separation patterns around the squares. int vspSize = 7; // Left top corner. embedVerticalSeparationPattern(vspSize, 0, matrix); // Right top corner. embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix); // Left bottom corner. embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix); }
static void embedDataBits(BitArray dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { if (x == 6) { x--; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; i++) { int xx = x - i; if (isEmpty(matrix.get(xx, y))) { boolean bit; if (bitIndex < dataBits.getSize()) { bit = dataBits.get(bitIndex); bitIndex++; } else { bit = false; } if (maskPattern != -1 && MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit = !bit; } matrix.set(xx, y, bit); } } y += direction; } direction = -direction; y += direction; x -= 2; } if (bitIndex != dataBits.getSize()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits .getSize()); } }
private static void encodingECI(int eci, StringBuilder sb) throws WriterException { if (eci >= 0 && eci < LATCH_TO_TEXT) { sb.append('Ο'); sb.append((char) eci); } else if (eci < 810900) { sb.append('Ξ'); sb.append((char) ((eci / LATCH_TO_TEXT) - 1)); sb.append((char) (eci % LATCH_TO_TEXT)); } else if (eci < 811800) { sb.append('Ν'); sb.append((char) (810900 - eci)); } else { throw new WriterException("ECI number not in valid range from 0..811799, but was " + eci); } }
/** * 根据宽高生成二维码 * * @param width * @param height * @param source * @return */ public static Bitmap createQRCode(int width, int height, String source) { try { if (TextUtils.isEmpty(source)) { return null; } Hashtable<EncodeHintType, String> hints = new Hashtable<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(source, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (bitMatrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } else { pixels[y * width + x] = 0xffffffff; } } } // sheng chen de er wei ma 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; }
private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { int pdpWidth = POSITION_DETECTION_PATTERN[0].length; embedPositionDetectionPattern(0, 0, matrix); embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); embedHorizontalSeparationPattern(0, 7, matrix); embedHorizontalSeparationPattern(matrix.getWidth() - 8, 7, matrix); embedHorizontalSeparationPattern(0, matrix.getWidth() - 8, matrix); embedVerticalSeparationPattern(7, 0, matrix); embedVerticalSeparationPattern((matrix.getHeight() - 7) - 1, 0, matrix); embedVerticalSeparationPattern(7, matrix.getHeight() - 7, matrix); }
@Test public void TestCreateBufferedImages() throws IOException,WriterException{ String bedURLs[] = new String[2]; bedURLs[0]= "http://localhost:2538/bed/bed1?qr=true"; bedURLs[1] = "http://localhost:2538/bed/bed2?qr=true"; System.out.println(QRCodes.createBufferedImages(bedURLs).get(0)); List<BufferedImage> qrCodeImages = new ArrayList<BufferedImage>(); for(int i = 0; i < 2; i++) { qrCodeImages.add(createQRFromBedURL(bedURLs[i])); } //test to see if the width is 300 of the created buffered image assertEquals("they should return same buffered images", qrCodeImages.get(0).toString().contains("width = 300"),QRCodes.createBufferedImages(bedURLs).get(0).toString().contains("width = 300") ); }
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException { if (format == BarcodeFormat.UPC_A) { return this.subWriter.encode(preencode(contents), BarcodeFormat.EAN_13, width, height, hints); } throw new IllegalArgumentException("Can only encode UPC-A, but got " + format); }
@Deprecated public BitMatrix encode(String contents, BarcodeFormat format, boolean compact, int width, int height, int minCols, int maxCols, int minRows, int maxRows, Compaction compaction) throws WriterException { Map<EncodeHintType, Object> hints = new EnumMap(EncodeHintType.class); hints.put(EncodeHintType.PDF417_COMPACT, Boolean.valueOf(compact)); hints.put(EncodeHintType.PDF417_COMPACTION, compaction); hints.put(EncodeHintType.PDF417_DIMENSIONS, new Dimensions(minCols, maxCols, minRows, maxRows)); return encode(contents, format, width, height, hints); }