我尝试使用itext
,但我找不到将条形码打印到图像的方法,我只找到了将条形码打印到PDF
的示例,我有一张信用卡图片,所以我需要在图像中绘制一个条形码(卡号),有人在itext
或另一个使用其他库的例子中有一个如何做的例子吗?
提前致谢。
答案 0 :(得分:0)
<强>解决方案:强>
基本上,您想要绘制条形码并创建.png。如果是这样的话 Buffered Image 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) {
...
}
它会创建一个图像,然后将其写入文件。
答案 1 :(得分:0)
我找到了一个解决方案,希望这有助于其他人,感谢所有
使用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);