2012-09-27 81 views
1

我能夠使用斑馬線條形碼庫,現在用生成條形碼...條碼生成與斑馬線

String text = "123456789101"; 

int width = 300; 
int height = 100; 
String imgFormat = "png"; 

BitMatrix bitMatrix = new UPCAWriter().encode(text, BarcodeFormat.UPC_A, width, height); 
MatrixToImageWriter.writeToStream(bitMatrix, imgFormat, new FileOutputStream(new File("C:\\code_.png"))); 
out.println("Success!"); 

我得到了我的輸出,與平面條碼圖像,但我想打印「文本(字符串文本= 「123456789101」;)'也是該圖像的底部,任何人都知道,請幫助我。

非常感謝。

回答

3

如果你的圖書館沒有實現這樣的事情,而且我認爲它不會在這裏沒有任何問題,否則你可以自己在條形碼圖片上打印代碼。請查詢this問題以獲得如何完成的簡要說明。

另一種選擇是在圖像下以明文形式輸出代碼 - 不確定它是否適合您。

UPD:您還可以嘗試Barcode4j庫。我認爲它可以做這樣的事情。

+0

什麼地方,我想顯示我的文字與條形碼圖像,我是新來這..我們有任何其他庫像zxing,我的意思是免費許可證。 – Bharath

+0

@John,我用一個可能有所幫助的圖書館更新了答案。 – svz

+0

謝謝你,我們是否有任何例子,像hello world這樣的東西,我看到了網站,但他們沒有指定任何例子。 – Bharath

0
You can Encode it Using EN_13 bellow class: 
      String barcode="123456789123"; //barcode must be 13 digit 
      ImageView ivBarcode; 
      EAN13 code = new EAN13(barcode); 
     Bitmap bitmap = code.getBitmap(860, 300); 
     ivBarcode.setImageBitmap(bitmap); 

/*****************************************************************/ 

    import android.content.Context; 
    import android.graphics.Bitmap; 
    import android.graphics.Canvas; 
    import android.graphics.Color; 
    import android.graphics.Paint; 
    import android.graphics.Rect; 

    public class EAN13 { 

     private static final String TAG = EAN13.class.getSimpleName(); 

     private String data; 
     Context context; 

     public EAN13(Context _context) { 
      context=_context; 
     } 

     public EAN13(String data){ 
      this.data = data; 
     } 

     public void setData(String data) { 
      this.data = data; 
     } 

     public String getData() { 
      return data; 
     } 


     public void init() { 
      //data = null; 
     } 

     public byte[] initBuffer() { 
      int sum = 0; 

      //add start code 4byte 
      sum = sum + 3; 
      //add middle code 5byte 
      sum = sum + 5; 
      //add end code 4 byte 
      sum = sum + 3; 
      //add encoded data 7byte * 12 
      sum = sum + (7 * 12); 

      // sum = 11 + 11 + 12 + (11*dataLen); 
      return new byte[sum]; 
     } 



     public byte[] encode() { 

      if(isVaildBarcodeData() == false) { 
       android.util.Log.e(TAG, "invalid data length!!"); 
       return null; 
      } 

      int len = data.length(); 
      int pos = 0; 

      init(); 
      byte[] buffer = initBuffer(); 

      int first_num = Integer.parseInt(data.substring(0, 1)); 
      byte[] patterns = EAN13Constant.FIRST_DIGIT[first_num]; 

      pos += appendData(EAN13Constant.START_PATTERN, buffer, pos, "START CODE"); 
      for(int i=1; i<len; i++) { 
       int num = Integer.parseInt(data.substring(i, i+1)); 

       byte code = patterns[(i-1)]; 

       if(code == EAN13Constant.L_CODE) { 
        pos += appendData(EAN13Constant.L_CODE_PATTERN[num], buffer, pos, "L code based number"); 
       } else if(code ==EAN13Constant.G_CODE) { 
        pos += appendData(EAN13Constant.G_CODE_PATTERN[num], buffer, pos, "G code based number"); 
       } else { // R-code 
        pos += appendData(EAN13Constant.R_CODE_PATTERN[num], buffer, pos, "R code based number"); 
       } 

       if(i == 6) { 
        pos += appendData(EAN13Constant.MIDDLE_PATTERN, buffer, pos, "MIDDLE CODE"); 
       } 
      } 

      pos += appendData(EAN13Constant.END_PATTERN, buffer, pos, "END CODE"); 

      return buffer; 
     } 



     public Bitmap getBitmap(int width, int height) { 
      byte[] code = encode(); 

      if(code == null) { 
       return null; 
      } 
      int inputWidth = code.length; 
      // Add quiet zone on both sides 
      int fullWidth = inputWidth + 6; // for empty(quiet) space 
      int outputWidth = Math.max(width, fullWidth); 
      int outputHeight = Math.max(1, height); 

      int multiple = outputWidth/fullWidth; 
      int leftPadding = (outputWidth - (inputWidth * multiple))/2; 

      //BitMatrix output = new BitMatrix(outputWidth, outputHeight); 
      Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
      Canvas canvas = new Canvas(bitmap); 
      // new antialised Paint 
      Paint bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
      // text color - #3D3D3D 
      bgPaint.setColor(Color.rgb(255, 255, 255)); 

      Rect bounds = new Rect(0, 0, width, height); 
      canvas.drawRect(bounds, bgPaint); 

      Paint barPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
      barPaint.setColor(Color.rgb(0, 0, 0)); 
      barPaint.setStrokeWidth(0); 

      for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { 
       if (code[inputX] == 1) { 
        //output.setRegion(outputX, 0, multiple, outputHeight); 
        android.util.Log.e(TAG, "outputX: " + outputX + ", ouputY: 0, multiple: " + multiple + ", outputHeight: " + outputHeight); 
        //canvas.drawRect(new Rect(outputX, 0, multiple, outputHeight), barPaint); 
        //canvas.drawText(text, x, y, paint) 
        //float left, float top, float right, float bottom 
        canvas.drawRect(outputX, 0, (outputX+multiple), outputHeight, barPaint); 
       } 
      } 
      return bitmap; 
     } 

     public int getSum() { 
      return getSum(); 
     } 

     public boolean isVaildBarcodeData() { 
      if(data == null) { 
       return false; 
      } 

      if(data.length() != 13) { 
       return false; 
      } 

      if(checkNumber(data) == false) { 
       return false; 
      } 

      return true; 
     } 


     private static boolean checkNumber(String data) { 
      int len = data.length(); 

      for(int i=0; i<len; i++) { 
       char ch = data.charAt(i); 
       if (ch < '0' || ch > '9') { 
        //if((ch < 48) || (ch > 57)) { 
        return false; 
       } 
      } 

      return true; 
     } 

     private int appendData(byte[] src, byte[] dst, int pos, String debugdata) { 

      System.arraycopy(src, 0, dst, pos, src.length); 

      if(debugdata != null) { 
       printByteArr(debugdata, src); 
      } 

      return src.length; 
     } 

     private void printByteArr(String msg, byte[] buff) { 
      if(buff == null) { 
       return; 
      } 

      StringBuilder sb = new StringBuilder(); 
      for(byte by: buff) { 
       sb.append(by); 
      } 
      android.util.Log.e(TAG, "char: " + msg + " barcode weight: " + sb.toString()); 
     } 

    } 

的EAN13Constant是在這裏:

public class EAN13Constant { 

public static final byte L_CODE = 0; 
public static final byte G_CODE = 1; 
public static final byte R_CODE = 2; 

public static final byte[][] FIRST_DIGIT = { 
    { L_CODE,L_CODE,L_CODE,L_CODE,L_CODE,L_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,L_CODE,G_CODE,L_CODE,G_CODE,G_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,L_CODE,G_CODE,G_CODE,L_CODE,G_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,L_CODE,G_CODE,G_CODE,G_CODE,L_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,G_CODE,L_CODE,L_CODE,G_CODE,G_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,G_CODE,G_CODE,L_CODE,L_CODE,G_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,G_CODE,G_CODE,G_CODE,L_CODE,L_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,G_CODE,L_CODE,G_CODE,L_CODE,G_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,G_CODE,L_CODE,G_CODE,G_CODE,L_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
    { L_CODE,G_CODE,G_CODE,L_CODE,G_CODE,L_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE,R_CODE }, 
}; 

public static final byte[] START_PATTERN = { 1, 0, 1 }; 

public static final byte[] MIDDLE_PATTERN = { 0, 1, 0, 1, 0 }; 

public static final byte[] END_PATTERN = { 1, 0, 1 }; 


// l-code 
public static final byte[][] L_CODE_PATTERN = { 
    { 0,0,0,1,1,0,1 }, 
    { 0,0,1,1,0,0,1 }, 
    { 0,0,1,0,0,1,1 }, 
    { 0,1,1,1,1,0,1 }, 
    { 0,1,0,0,0,1,1 }, 
    { 0,1,1,0,0,0,1 }, 
    { 0,1,0,1,1,1,1 }, 
    { 0,1,1,1,0,1,1 }, 
    { 0,1,1,0,1,1,1 }, 
    { 0,0,0,1,0,1,1 }, 
}; 

// g-code 
public static final byte[][] G_CODE_PATTERN = { 
    { 0,1,0,0,1,1,1 }, 
    { 0,1,1,0,0,1,1 }, 
    { 0,0,1,1,0,1,1 }, 
    { 0,1,0,0,0,0,1 }, 
    { 0,0,1,1,1,0,1 }, 
    { 0,1,1,1,0,0,1 }, 
    { 0,0,0,0,1,0,1 }, 
    { 0,0,1,0,0,0,1 }, 
    { 0,0,0,1,0,0,1 }, 
    { 0,0,1,0,1,1,1 }, 
}; 

// r-code 
public static final byte[][] R_CODE_PATTERN = { 
    { 1,1,1,0,0,1,0 }, 
    { 1,1,0,0,1,1,0 }, 
    { 1,1,0,1,1,0,0 }, 
    { 1,0,0,0,0,1,0 }, 
    { 1,0,1,1,1,0,0 }, 
    { 1,0,0,1,1,1,0 }, 
    { 1,0,1,0,0,0,0 }, 
    { 1,0,0,0,1,0,0 }, 
    { 1,0,0,1,0,0,0 }, 
    { 1,1,1,0,1,0,0 }, 
}; 
} 
+0

哪裏聲明EAN13Constant? – exequielc

1

是一個古老的線程,但如果有人仍然需要它...

import java.awt.Color; 
import java.awt.Font; 
import java.awt.FontMetrics; 
import java.awt.Graphics2D; 
import java.awt.RenderingHints; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.util.Hashtable; 

import com.google.zxing.BarcodeFormat; 
import com.google.zxing.EncodeHintType; 
import com.google.zxing.common.BitMatrix; 
import com.google.zxing.oned.Code128Writer; 
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 

// ... 
// vars width and height have image width and height (int) 
// var barcodeMessage has the text under the barcode 

// text 
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); // aux implementation 
Graphics2D g2d = img.createGraphics(); 
Font font = new Font("Times", Font.PLAIN, 11); 
g2d.setFont(font); 
FontMetrics fm = g2d.getFontMetrics(); 
int textWidth = fm.stringWidth(barcodeMessage); 
int textHeight = fm.getHeight(); 
g2d.dispose(); 
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
g2d = img.createGraphics(); 
g2d.setColor(backgroundColor); 
g2d.fillRect(0, 0, width, height); 
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); 
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); 
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); 
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); 
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); 
g2d.setFont(font); 
fm = g2d.getFontMetrics(); 
g2d.setColor(textColor); 
g2d.drawString(barcodeMessage, Math.round(Math.floor((width-textWidth)/2))-2, height-fm.getAscent()); 
g2d.dispose(); 

// barcode 
Code128Writer code128Writer = new Code128Writer(); 
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); 
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 
BitMatrix bitMatrix = code128Writer.encode(barcodeMessage, BarcodeFormat.CODE_128, width, height-textHeight-(2*fm.getAscent()), hintMap); 

// Make the BufferedImage that are to hold the Code128 
int matrixWidth = bitMatrix.getWidth(); 
int matrixHeight = bitMatrix.getHeight(); 

Graphics2D graphics = (Graphics2D) img.getGraphics(); 
graphics.setColor(textColor); 
for (int i = 0; i < matrixWidth; i++) { 
    for (int j = 0; j < matrixHeight; j++) { 
     if (bitMatrix.get(i, j)) { 
      graphics.fillRect(i, j+fm.getAscent(), 1, 1); 
     } 
    } 
} 

您可以用寬度和高度變量玩,字體,條形碼類型等。

0

此方法允許繪製一個白色的矩形,並在其底部編碼的字符串使用java.awt

/** 
* 
* @param codeS String coded to a barcode 
* @param qrfile File with generated image when completed. 
* @param width in pixels 
* @param height in pixels 
* @param fontSize in pixels 
* @throws Exception 
*/ 
public void generateBarCode(String codeS, 
     File qrfile, 
     int width, 
     int height, 
     int fontSize) throws Exception { 
    FileOutputStream qrCode = null; 
    try { 
     // Encode URL in QR format 
     BitMatrix matrix; 
     com.google.zxing.Writer writer = new Code128Writer(); 
     //writer = new QRCodeWriter(); in case of BarcodeFormat.QR_CODE 
     try { 
      matrix = writer.encode(codeS, BarcodeFormat.CODE_128, width, height); 
     } catch (WriterException e) { 
      //logger.error("Error generando el QR", e); 
      throw new Exception("Error generando el QR"); 
     } 
     // Create buffered image to draw to 
     BufferedImage image = new BufferedImage(width, 
       height, BufferedImage.TYPE_INT_RGB); 
     // Iterate through the matrix and draw the pixels to the image 
     for (int y = 0; y < height; y++) { 
      for (int x = 0; x < width; x++) { 
       int grayValue = (matrix.get(x, y) ? 0 : 1) & 0xff; 
       image.setRGB(x, y, (grayValue == 0 ? 0 : 0xFFFFFF)); 
      } 
     } 
     Graphics graphics = image.getGraphics(); 
     graphics.drawImage(image, 0, 0, null); 


     Font f = new Font("Arial", Font.PLAIN, fontSize); 

     FontRenderContext frc = image.getGraphics().getFontMetrics().getFontRenderContext(); 
     Rectangle2D rect = f.getStringBounds(codeS, frc); 
     graphics.setColor(Color.WHITE); 

     //add 10 pixels to width to get 5 pixels of padding in left/right 
     //add 6 pixels to height to get 3 pixels of padding in top/bottom 
     graphics.fillRect(
       (int)Math.ceil((image.getWidth()/2)-((rect.getWidth()+10)/2)), 
       (int)Math.ceil(image.getHeight() - (rect.getHeight()+6)), 
       (int)Math.ceil(rect.getWidth()+10), 
       (int)Math.ceil(rect.getHeight()+6)); 
     // add the watermark text 
     graphics.setFont(f); 
     graphics.setColor(Color.BLACK); 
     graphics.drawString(codeS, 
       (int)Math.ceil((image.getWidth()/2)-((rect.getWidth())/2)), 
       (int)Math.ceil(image.getHeight() - 6)); 
     graphics.dispose(); 

     qrCode = new FileOutputStream(qrfile); 
     ImageIO.write(image, "png", qrCode); 

    } catch (Exception ex) { 
     throw new Exception("Error generando el QR"); 
    } finally { 
     try { 
      qrCode.close(); 
     } catch (Exception ex) { 
      throw new Exception("Error generando el QR"); 
     } 
    } 
}