Skip to content

Instantly share code, notes, and snippets.

@gorrotowi
Created August 19, 2016 02:11
Show Gist options
  • Save gorrotowi/232533ea8c27b473aace5ec7c1226216 to your computer and use it in GitHub Desktop.
Save gorrotowi/232533ea8c27b473aace5ec7c1226216 to your computer and use it in GitHub Desktop.
Encode data with Android XZing
//Global Objects and variables
ImageView imgBarcode;
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap bmp;
//Implementation
bmp = encodeAsBitmap("1234567890", BarcodeFormat.CODE_128, 800, 200);
imgBarcode.setImageBitmap(bmp);
//Method Encode
public Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int imgWidth, int imgHeight) {
if (contents == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contents, format, imgWidth, imgHeight, hints);
} catch (WriterException e) {
e.printStackTrace();
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;
}
private static String guessAppropriateEncoding(CharSequence contents) {
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment