簡體   English   中英

使用Java創建條形碼並將其繪制到現有圖像上

[英]create barcode and draw it to an existing image using java

我嘗試使用itext但是找不到將條形碼打印到圖像的方法,僅找到了將條形碼打印到PDF示例,我擁有信用卡的圖像,因此需要繪制條形碼(卡號)上的圖像,是否有人在itext或使用另一個庫的另一個示例中提供了示例?

提前致謝。

解:

基本上,您想繪制條形碼並創建一個.png。 如果是這種情況, 緩沖圖像API應該可以解決問題

BufferedImage bufferedImage = new        
BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.getGraphics();

g.fillRect(0,0, 20,20); // draws barcode

寫入.png的示例

try {
    // retrieve image
    BufferedImage bi = getMyImage();
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    ...
}

它創建一個圖像,然后將其寫入文件。

我找到了解決方案,希望對其他人有幫助

使用itext創建條形碼:

Barcode39 barcode = new Barcode39();
barcode.setCode("7001390283546141");
barcode.setBarHeight(40);

Image img = barcode.createAwtImage(Color.BLACK, Color.WHITE);

BufferedImage outImage = new BufferedImage(img.getWidth(null), img.getHeight(null),BufferedImage.TYPE_INT_RGB);

outImage.getGraphics().drawImage(img, 0, 0, null);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ImageIO.write(outImage, "png", bytesOut);
bytesOut.flush();
byte[] pngImageData = bytesOut.toByteArray();
FileOutputStream fos = new FileOutputStream("C:/results/barcode.jpg");
fos.write(pngImageData);
fos.flush();
fos.close();

創建條形碼圖像后

final BufferedImage image1 = ImageIO.read(new File("C:/results/image.jpg"));
final BufferedImage image2 = ImageIO.read(new File("C:/results/barcode.jpg"));

Graphics g = image2.getGraphics();
g.drawImage(image2, 0, 0, image2.getWidth(), image2.getHeight(), null);
g.dispose();

final int xMax = image1.getWidth() - image2.getWidth();
final int yMax = image1.getHeight() - image2.getHeight();

Graphics g2 = image1.getGraphics();
Random random = new Random();
int x = random.nextInt(xMax);
int y = random.nextInt(yMax);

g2.drawImage(image2, x, y, null);
g2.dispose();

File outputfile = new File("C:/results/final.jpg");
ImageIO.write(image1, "png", outputfile);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM