I have been trying to use Barcode4J on Android but I can not seem to get BufferedImage class and I am not sure how I am suppose to replace this class with anything from Android.graphic.* which does not seem to have something similar. Also the Barcode4J will not accept anything other then BufferedImage object for obvious reasons.
What could I use instead or is there a Barcode generator Lib better suited for Android?
I have tried Barcode4Android which really made no sense since the Example they gave on GIT used BufferedImage from the java.awt.image.BufferedReader package also >.< . So I was back at step 1.
I actually just need the QR generating function.
My Questions.
1. Is there an Alternative to Barcode4J for Android.
2. OR is there a work around for my problem ?
Here is one of the Java tutorials I tried to use
public class HelloExample1 {
public static void main(String[] args) throws Exception{
//Create the barcode bean
Code39Bean bean = new Code39Bean();
final int dpi = 150;
//Configure the barcode generator
bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar, width exactly one pixel
bean.setWideFactor(3);
bean.doQuietZone(false);
//Open output file
File outputFile = new File("resources"+"/"+"images"+"/"+"out.png");
OutputStream out = new FileOutputStream(outputFile);
try {
//Set up the canvas provider for monochrome PNG output
BitmapCanvasProvider canvas = new BitmapCanvasProvider(
out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
//Generate the barcode
bean.generateBarcode(canvas, "Hello World");
//Signal end of generation
canvas.finish();
} finally {
out.close();
}
}
}
Try Zxing, its a code generator and reader, easy to use in Android. Hope it helps.
Related
I simply want to add color to the background of the PDF that I'm generating with this library.
I want my pages to have color as the background or even a picture. The documentation got me dizzy. There are no useful or meaningful descriptions; it can hardly be called documentation.
Why is this simple task so hard to achieve with this library? Do I have to go through the trouble of reading a whole book, just to understand how to use a library?
There is no straightforward answer online, or in their "examples", but I managed to find a similar question about having various page background-colors in the PDF file here.
UPDATE: It seems that the iText-7 eBooks/resources have been updated during the past 3 years. The following links are
working as of 21/07/2021.
NEW EBOOK URL FOR ITEXT-7 BUILDING BLOCKS HERE
VARIOUS CODE EXAMPLES HERE
ALL RESOURCES INDEX HERE
The solution is overly complex, in my opinion. This is just background color and it is a task that could have been made considerably less time consuming to understand. Making a framework as modular and flexible as possible is understandable, but sometimes there are some trivial tasks that people just want to get done quickly.
Anyway, here is the solution for anyone who might have the same problem as I did:
//Class that creates the PDF
public class PdfCreator {
//Helper class so we can add colour to our pages when we call it from outer class
private static class PageBackgroundsEvent implements IEventHandler {
#Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfPage page = docEvent.getPage();
PdfCanvas canvas = new PdfCanvas(page);
Rectangle rect = page.getPageSize();
//I used custom rgb for Color
Color bgColour = new DeviceRgb(255, 204, 204);
canvas .saveState()
.setFillColor(bgColour)
.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight())
.fillStroke()
.restoreState();
}
}
//PATH_OF_FILE is the path that the PDF will be created at.
String filename = PATH_OF_FILE + "/myFile.pdf";
OutputStream outputStream = new FileOutputStream(new File(filename));
PdfWriter writer = new PdfWriter(outputStream);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, new PageBackgroundsEvent());
PageSize pageSize = pdfDoc.getDefaultPageSize();
Document document = new Document(pdfDoc, pageSize);
document.close();
}
Background images can be added the same way! See this link
to set a background image :
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, event -> {
new PdfCanvas(((PdfDocumentEvent)event).getPage())
.addImageAt(ImageFactory.create("filename.png"), 50f, 50f, true);
});
I'm trying to hide a message inside a .gif for a steganography project.
I've converted the input gif to an ArrayList of BufferedImages ana applied my steganography algorithm.
But, i came across an issue with converting the ArrayList of BufferedImages back to a .gif.
I used this GifSequenceWriter class to convert the BufferedImages array to a new .gif after getting the original delay between frames from the original gif image metadata.
File encoded_img = new File("output.gif");
ImageOutputStream output = new FileImageOutputStream(encoded_img);
GifSequenceWriter writer = new GifSequenceWriter(output, frames.get(0).getType(), delayTimeMS, true);
writer.writeToSequence(frames.get(0));
for(int k=1; k<frames.size()-1; k++) {
writer.writeToSequence(frames.get(k));
}
writer.close();
output.close();
But, the resulting .gif looks really bad, and i've saved the individual frames with and without the steganography algorithm and they look fine. You can check out an example of the original image, the 10 saved frames and the resulting .gif here.
Is there a better way to create .gifs in java?
Thanks in advance.
There's a problem with the the GifSequenceWriter when using palette images (BufferedImage.TYPE_BYTE_INDEXED with IndexColorModel). This will create metadata based on a default 216 color palette (the web safe palette), which is clearly different from the colors in your image.
The problematic lines in GifSequenceWriter:
ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(imageType);
imageMetaData = gifWriter.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam);
Instead, the metadata should be based on the color palette in the index color model of your image. But the good news is, it works fine without it.
You can simply use:
GifSequenceWriter writer = new GifSequenceWriter(output, BufferedImage.TYPE_INT_ARGB, delayTimeMS, true);
...and the writer will automatically create the palette as needed, from your actual image data.
It's also possible to fix the GifSequenceWriter, to accept an ImageTypeSpecifier instead of the int imageType, however, this will only work if all frames use the same palette, I think:
public GifSequenceWriter(
ImageOutputStream outputStream,
ImageTypeSpecifier imageTypeSpecifier,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
// my method to create a writer
gifWriter = getWriter();
imageWriteParam = gifWriter.getDefaultWriteParam();
imageMetaData = gifWriter.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam);
// ... rest of the method unchanged.
Usage:
ColorModel cm = firstImage.getColorModel();
ImageTypeSpecifier imageType = new ImageTypeSpecifier(cm, cm.createCompatibleSampleModel(1, 1));
GifSequenceWriter writer = new GifSequenceWriter(output, imageType, delayTimeMS, true);
Does anyone have a way of storing a BufferedImage with transparency as BMP in Java? Preferably using the ImageIO API.
For some reason I can't write a BMP in ARGB (BGRA) format, even though the BMP has supported alpha channel since, at least, Win95. I can, however, easily write the same image as a PNG. It also works fine storing an image without alpha, like TYPE_INT_RGB or TYPE_3BYTE_BGR.
Consider the following code snippet:
public static void main(String[] args) throws IOException {
if (!ImageIO.write(new BufferedImage(300, 200, BufferedImage.TYPE_INT_ARGB), "BMP", new File("foo.bmp"))) {
System.err.println("Couldn't write BMP!");
}
if (!ImageIO.write(new BufferedImage(300, 200, BufferedImage.TYPE_INT_ARGB), "PNG", new File("foo.png"))) {
System.err.println("Couldn't write PNG!");
}
}
Output:
Couldn't write BMP!
In BMPImageWriterSpi:
public boolean canEncodeImage(ImageTypeSpecifier type) {
...
if (!(numBands == 1 || numBands == 3))
return false;
I'm afraid Java doesn't support 32 bit BMPs. You'd have to write your own or find an existing library (ImageJ comes to mind although I don't know if it supports BMP). Wikipedia is very elaborate on the file format and it looks quite easy, even giving a complete field-by-field example of a 32-bit BMP.
I am trying to read 2D Data matrix barcode using zxing library(GenericMultipleBarcodeReader). I have multiple barcodes on a single image.
The problem is that the efficiency of the zing reader is very low, it
recognizes 1 barcode from image 1.png and no barcode from image 2.png which has 48 barcodes. Is there
any way to get 100% efficiency or any other library which results 100%
My code to read barcode is:
public static void main(String[] args) throws Exception {
BufferedImage image = ImageIO.read(new File("1.png"));
if (image != null) {
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
DataMatrixReader dataMatrixReader = new DataMatrixReader();
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
GenericMultipleBarcodeReader reader = new GenericMultipleBarcodeReader(
dataMatrixReader);
Result[] results = reader.decodeMultiple(bitmap, hints);
for (Result result : results) {
System.out.println(result.toString());
}
}
}
And images I used are:
Please help to resolve this issue.
Thanks
It doesn't quite work this way. It will not read barcodes in a grid, as it makes an assumption that it can cut up the image in a certain way that won't be compatible with grids. You will have to write your own method to cut up the image into scannable regions.
It is also the case that the Data Matrix decoder assumes the center of the image is inside the barcode. This is another reason you need to pre-chop the image into squares around the cylinders and then scan. It ought to work fairly well then.
An alternative solution is to consider a barcode engine that can detect multiple barcodes in various orientations on one document. If you're running on Windows, the ClearImage Barcode SDK has a Java API and should be able to handle your needs without pre-processing. You can test if their engine can read your image using their Online Barcode Reader.
Some sample code:
public static void testDataMatrix () {
try {
String filename = "1.png ";
CiServer objCi = new CiServer();
Ci = objCi.getICiServer();
ICiDataMatrix reader = Ci.CreateDataMatrix(); // read DataMatrix Barcode
reader.getImage().Open(filename, 1);
int n = reader.Find(0); // find all the barcodes in the doc
for (i = 1; i <= n; i++) {
ICiBarcode Bc = reader.getBarcodes().getItem(i); // getItem is 1-based
System.out.println("Barcode " + i + " has Text: " + Bc.getText());
}
} catch (Exception ex) {System.out.println(ex.getMessage());}
}
Disclaimer: I've done some work for Inlite in the past.
-Edit-
FYI.. I am converting b&w documents scanned in as greyscale or color.
1)The first solution worked, it just reversed black & white (black background, white text). It also took nearly 10 minutes.
2)The JAI solution in the 2nd answer didn't work for me. I tried it before posting here.
Has anyone worked with other libraries free or pay that handle image manipulation well?
-Original-
I am trying to convert an PNG to a bitonal TIFF using Java ImageIO. Has anyone had any luck doing this? I have got it to convert from PNG to TIFF. I am not sure if I need to convert the BufferedImage (PNG) that I read in or convert on the TIFF as I write it. I have searched and searched but nothing seems to work? Does anyone have an suggestions where to look?
Here is the code that converts...
public static void test() throws IOException {
String fileName = "4848970_1";
// String fileName = "color";
String inFileType = ".PNG";
String outFileType = ".TIFF";
File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType);
InputStream fis = new BufferedInputStream(new FileInputStream(fInputFile));
ImageReaderSpi spi = new PNGImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = reader.read(0);
int[] xi = bi.getSampleModel().getSampleSize();
for (int i : xi) {
System.out.println("bitsize " + i);
}
ImageWriterSpi tiffspi = new TIFFImageWriterSpi();
TIFFImageWriter writer = (TIFFImageWriter) tiffspi.createWriterInstance();
// TIFFImageWriteParam param = (TIFFImageWriteParam) writer.getDefaultWriteParam();
TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US);
String[] strings = param.getCompressionTypes();
for (String string : strings) {
System.out.println(string);
}
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("LZW");
File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType);
OutputStream fos = new BufferedOutputStream(new FileOutputStream(fOutputFile));
ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
writer.write(null, new IIOImage(bi, null, null), param);
ios.flush();
writer.dispose();
ios.close();
}
I have tried changing the compression to type "CCITT T.6" as that appears to be what I want, but I get an error " Bits per sample must be 1 for T6 compression! " Any suggestion would be appreciated.
Most likely, you want something like this to convert to 1 bit before you save to TIFF with CCITT compression.
To expound a little bit - be aware that converting from other bit depths to 1 bit is non-trivial. You are doing a data reduction operation and there are dozens of domain specific solutions which vary greatly in output quality (blind threshold, adaptive threshold, dithering, local threshold, global threshold and so on). None of them are particularly good at all image types (adaptive threshold is pretty good for documents, but lousy for photographs, for example).
As plinth said, you have to do the conversion, Java won't do it magically for you...
If the PNG image is already black & white (as it seems, looking at your comment), using a threshold is probably the best solution.
Somebody seems to have the same problem: HELP: how to compress the tiff. A solution is given on the thread (untested!).