2

我能够使用 zxing 条码库生成条码,我正在使用...

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”;)',任何知道的人请帮助我。

非常感谢。

4

4 回答 4

3

如果你的库没有实现这样的东西,我想它没有,否则这里没有问题,你可以自己在条形码图像上打印你的代码。检查问题以简要说明如何完成。

另一种选择是在图像下以纯文本形式输出代码 - 不确定它是否适合您。

UPD:您也可以尝试Barcode4j库。我认为它可以做这样的事情。

于 2012-09-27T09:42:44.027 回答
3

是一个旧线程,但如果有人仍然需要它......

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);
        }
    }
}
graphics.dispose();

您可以使用宽度和高度变量、字体、条形码类型等。

于 2014-10-28T14:50:18.427 回答
1

此方法允许使用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");
        }
    }
}
于 2017-07-01T14:31:45.093 回答
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 },
};
}
于 2014-05-03T10:52:53.380 回答