Create QR code image from String

public Bitmap createBitmap(String str, Context context) throws WriterException {

    int wd = UiUtil.getPixelFromDp(100);
    int pinkColor = context.getResources().getColor(R.color.black);
    int whiteColor = context.getResources().getColor(R.color.white);

    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(1);

    hints.put(EncodeHintType.MARGIN, 0);


    BitMatrix result;
    try {
        result = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, wd, wd, hints);
    } catch (IllegalArgumentException iae) {
        // TODO Unsupported format
        return null;
    }

    //Change color pixel
    int w = result.getWidth();
    int h = result.getHeight();
    int[] pixels = new int[w * h];
    for (int y = 0; y < h; y++) {
        int offset = y * w;
        for (int x = 0; x < w; x++) {
            pixels[offset + x] = result.get(x, y) ? pinkColor : whiteColor;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, wd, 0, 0, w, h);

    return bitmap;
}
Advertisements