Android如何从imageview转换条形码和从收据打印机打印

时间:2017-04-12 07:33:11

标签: android imageview barcode thermal-printer

我设法从收据打印机打印出条形码我已经将imageview转换为字节格式,但没有从收据打印机打印出来。任何解决我的问题的建议,或者有另一种方法可以通过收据打印机打印出条形码。

这是我如何将imageview转换为byte并使用OutputStream打印出条形码。

       ImageView iv = (ImageView) findViewById(R.id.imageView);
       // barcode data
       String barcode_data = "asdasdasd";
       OutputStream socketOut = null;
       // barcode image
       Bitmap bitmap = null;

       try {

             bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 1000, 1000);
             iv.setImageBitmap(bitmap);
             bitmap = ((BitmapDrawable) iv.getDrawable()).getBitmap();
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
             byte[] imageInByte = baos.toByteArray();
             try {
                    socketOut.write(imageInByte);
                 } catch (IOException e) {
                    e.printStackTrace();
                 }


             } catch (WriterException e) {
               e.printStackTrace();
           }

Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) 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, Object>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result;
    try {
        result = writer.encode(contentsToEncode, format, img_width, img_height, 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;
}

private static String guessAppropriateEncoding(CharSequence contents) {
    // Very crude at the moment
    for (int i = 0; i < contents.length(); i++) {
        if (contents.charAt(i) > 0xFF) {
            return "UTF-8";
        }
    }
    return null;
}

0 个答案:

没有答案