Wednesday, February 21, 2018

create barcode and draw it to an existing image using java

https://stackoverflow.com/questions/38230667/create-barcode-and-draw-it-to-an-existing-image-using-java

I found a solution,hope this help someone else, thanks to all
Create the barcode using 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();
After create the barcode image
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);

No comments: