I'm using iText to create a PDF417 bar code like so:
private InputStream getBarcode() throws Exception {
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setText("Sample bar code text");
Image image = barcode.getImage();
image.scalePercent(50, 50 * barcode.getYHeight());
return new ByteArrayInputStream(image.getRawData());
}
I need to convert the CCITT format returned by barcode.getImage() to either JPG, GIF, or PNG so I can include it in a document I'm creating in JasperReports.
How about something like this?
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setText("Bla bla");
java.awt.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://barcode.png");
fos.write( pngImageData);
fos.flush();
fos.close();
The solution I came up with:
private Image getBarcode() throws Exception {
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setText("Sample bar code text");
barcode.setAspectRatio(.25f);
return barcode.createAwtImage(Color.BLACK, Color.WHITE);
}
JasperReports supports the java.awt.Image type for images used in a report.
Related
I have a function generateImageOutput below to write BufferedImage to jpeg file.
public boolean generateImageOutput(BufferedImage image, String filename){
//The image is written to the file by the writer
File file = new File( projectFolder+"/data/"+filename+".jpg");
//Iterator containing all ImageWriter (JPEG)
Iterator encoder = ImageIO.getImageWritersByFormatName("JPEG");
ImageWriter writer = (ImageWriter) encoder.next();
//Compression parameter (best quality)
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(1.0f);
//Try to write the image
try{
ImageOutputStream outputStream = ImageIO.createImageOutputStream(file);
writer.setOutput(outputStream);
writer.write(null, new IIOImage(image, null, null), param);
outputStream.flush();
writer.dispose();
outputStream.close();
}catch(IOException e){
e.printStackTrace();
System.out.println(e.toString());
return false;
}
return true;
}
It works for some, but it fails for a BufferedImage converted from base64 string:
String encodedString = JSON.parseObject(string).getString("image");
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
buffered_image = ImageIO.read(bis);
When writing the above buffered_image to jpeg using generateImageOutput, it raises exception :
javax.imageio.IIOException: Bogus input colorspace
at java.desktop/com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeImage(Native Method)
at java.desktop/com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeOnThread(JPEGImageWriter.java:1007)
at java.desktop/com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(JPEGImageWriter.java:371)
The string encodedString has no issue, I have sucessfully converted it to an image online.
How can I resolve the exception ?
According to #J.doe Alpha channel must be remove. I have a code that removes the Alpha channel. The code below was to determine whether or not the image has alpha channel. If the image has alpha channel it will create an image without alpha channel.
private static BufferedImage removeAlphaChannel(BufferedImage img) {
if (!img.getColorModel().hasAlpha()) {
return img;
}
BufferedImage target = createImage(img.getWidth(), img.getHeight(), false);
Graphics2D g = target.createGraphics();
// g.setColor(new Color(color, false));
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.drawImage(img, 0, 0, null);
g.dispose();
return target;
}
private static BufferedImage createImage(int width, int height, boolean hasAlpha) {
return new BufferedImage(width, height, hasAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
}
Finally I find that the reason is the image has an ALPHA channel.
Looks like JPEG doesn't handle the alpha channel correctly in this context. For me saving the image as PNG did the trick.
I want to send ImageIcon to database using jdbc.
I need to File object to do that.
How to convert ImageIcon to File wihout saving it into disk?
File fBlob = new File(imageIcon.getImage());
FileInputStream is = new FileInputStream ( fBlob );
preparedStatement.setBinaryStream (3, is, (int) fBlob.length() );
May be you could try to get a byte array from the imageIcon and then write it to the database. Something like this :
BufferedImage bi = getBufferedImage(imageIcon.getImage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, formatType, baos);
byte[] byteArray= baos.toByteArray();
preparedStatement.setBytes(1, byteArray);
EDIT :
Use this method to convert the Image to a BufferedImage :
public static BufferedImage getBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
BufferedImage bimage = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
I created a pdf using the iText 2.1.7 library. The Pdf (barcodes.pdf) contains a barcode with some text at the bottom. Additionally I saved this barcode as an image (barcode.png), however then the text at bottom is lost.
How do I create the barcode image which also contains the text at bottom?
String RESULT = "c:/BarCodeQRCodeGenerator/barcodes.pdf";
Document document = new Document(new Rectangle(340, 842));
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.open();
PdfContentByte cb = writer.getDirectContent();
document.add(new Paragraph("Barcode 128"));
Barcode128 code128 = new Barcode128();
code128.setCode("1234567890");
Image image = code128.createImageWithBarcode(cb, null, null)
document.add(image);
java.awt.Image rawImage = code128.createAwtImage(Color.BLACK, Color.WHITE);
BufferedImage outImage = new BufferedImage(rawImage.getWidth(null), rawImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
outImage.getGraphics().drawImage(rawImage, 0, 0, null);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ImageIO.write(outImage, "png", bytesOut);
bytesOut.flush();
byte[] pngImageData = bytesOut.toByteArray();
FileOutputStream fos = new FileOutputStream("c:/BarCodeQRCodeGenerator/barcode.png");
fos.write(pngImageData);
fos.close();
In your code you forgot to close the document. The solution is not so easy using the plain iText classes. Thus I used barcode4j (to test the example you need to download it and put it in your classpath):
Code128Bean code128 = new Code128Bean();
code128.setHeight(15f);
code128.setModuleWidth(0.3);
code128.setQuietZone(10);
code128.doQuietZone(true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
code128.generateBarcode(canvas, "1234567890");
canvas.finish();
//write to png file
FileOutputStream fos = new FileOutputStream("barcode.png");
fos.write(baos.toByteArray());
fos.flush();
fos.close();
//write to pdf
Image png = Image.getInstance(baos.toByteArray());
png.setAbsolutePosition(400, 685);
png.scalePercent(25);
Document document = new Document(new Rectangle(595, 842));
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("barcodes.pdf"));
document.open();
document.add(png);
document.close();
writer.close();
I have this method here, which converts an image to a byte array.
public byte[] imageToCompressedByteArray(Image image) throws IOException {
//load the image
String f = "C:\\Users\\mamed\\Documents\\NetBeansProjects\\Main\\src\\resources\\accept.png";
image = ImageIO.read(new FileInputStream(new File(f)));
// get image size
int width = image.getWidth(null);
int height = image.getHeight(null);
try {
int[] imageSource = new int[width * height];
PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, imageSource, 0, width);
pg.grabPixels();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
GZIPOutputStream zippedStream = new GZIPOutputStream(byteStream);
ObjectOutputStream objectStream = new ObjectOutputStream(zippedStream);
objectStream.writeShort(width);
objectStream.writeShort(height);
objectStream.writeObject(imageSource);
objectStream.flush();
objectStream.close();
return byteStream.toByteArray();
}
catch (Exception e) {
throw new IOException("Error storing image in object: " + e);
}
}
However, i can't get this to work, i mean, it can't load the image and convert it, and i don't have an idea what the problem can be.
Are you sure the image path is correct and the loaded image is not corrupted image.
I not modified your code and I can see 1778416 byes its read from the image file.
I do not see anything wrong with the program. Maybe your image file is corrupted or image path is not correct.
I need to create a barcode image in java using jasperreports, currently I'm doing this saving the image file on disk, but I need to do it without saving the image on disk. I need to create the barcode image in memory an then send it to iReport as a parameter.
This is what I have done:
Map<String, Object> parameters = new HashMap<String, Object>();
String imagePath = "\\\\netw\\barCode.jpg";
parameters.put("rutaCodigoBarrasVal", imagePath);
Barcode barCode = BarcodeFactory.createPDF417("1234567890");
barCode.setDrawingText(false);
barCode.setBarHeight(33);
barCode.setBarWidth(207);
FileOutputStream fOS = new FileOutputStream(imagePath);
BarcodeImageHandler.writeJPEG(barCode, fOS);
fOS.close();
What can I do?
You should first try to write the Barcode into a byte array or InputStream, looking at your library documentation.
JasperReports supports passing an image as a InputStream parameter, and draw that in the report.
InputStream imageStream = ...;
parametros.put("image", imageStream );
From JasperReports, receive that parameter as java.io.InputStream, then draw it with an image widget and the following properties:
Image Expression: $P{image}
Expression Class: java.io.InputStream
I hope it helps.
Finally this is what I did using barcode4j library:
ByteArrayOutputStream os = new ByteArrayOutputStream();
PDF417Bean barCode = new PDF417Bean();
boolean antiAlias = false;
int orientation = 0;
int dpi = 300;
BitmapCanvasProvider canvas = new BitmapCanvasProvider(dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation);
BarcodeDimension dim = new BarcodeDimension(207, 42);
canvas.establishDimensions(dim);
barCode.setColumns(7);
barCode.generateBarcode(canvas, codeToConvert);
canvas.finish();
String mime = MimeTypes.MIME_JPEG;
os = new ByteArrayOutputStream();
final BitmapEncoder encoder = BitmapEncoderRegistry.getInstance(mime);
encoder.encode(canvas.getBufferedImage(), os, mime, dpi);
fis = new ByteArrayInputStream(os.toByteArray());