I do not know a way to do this directly on an object of type Barcode
, since it does not respect the size, the preferred size, the minimum size , etc. and even if it has some utility for it. I looked at version 1.5 and did not have it.
One way to do this is to change the size of the original image it generates, retrieving it from Barcode
.
You can retrieve BufferedImage
from object Barcode
like this:
final BufferedImage originalImage = BarcodeImageHandler.getImage(barcode);
Now we need to create the new image representation, using 302
( equivalent approximate value to 8cm ) of width and the original height. It would look something like this:
final int originalHeight = originalImage.getHeight();
final BufferedImage resizedImage = new BufferedImage(302, originalHeight, originalImage.getType());
Then we need to create the graphic representation of this image and draw it with the new measurements in the new image:
final Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, 302, originalHeight, null);
g.dispose();
Now, here we have the image resized, so just do whatever it takes. To save to disk, as you are doing, you can do this:
final File f = new File("F:/barcode.png");
ImageIO.write(resizedImage, "PNG", f);
A complete example would be this:
final Barcode barcode = BarcodeFactory.createCode128C(chave);
barcode.setDrawingText(false);
barcode.setBarHeight(60);
barcode.setBarWidth(2);
final BufferedImage originalImage = BarcodeImageHandler.getImage(barcode);
final int originalHeight = originalImage.getHeight();
final BufferedImage resizedImage = new BufferedImage(302, originalHeight, originalImage.getType());
final Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, 302, originalHeight, null);
g.dispose();
final File f = new File("F:/barcode.png");
ImageIO.write(resizedImage, "PNG", f);
You generated this bar code:
Fromthisoriginal:
This is an example and you can see other things like scale in the new image, you will find lots of reference on the internet how to do this =)