Trouble generating Barcode using ZXing library with large data - java

I need to generate barcode in 128A format with data: 900000588548001100001305000000000207201512345.6|12345.7
I'm using ZXing library and Here is my method:
private void barcodeGenerator(String data)
{
try
{
com.google.zxing.MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix bm = writer.encode(data, BarcodeFormat.CODE_128, 700, 200);
Bitmap ImageBitmap = Bitmap.createBitmap(700, 200, Config.ARGB_8888);
for (int i = 0; i < 700; i++)
{//width
for (int j = 0; j < 200; j++)
{//height
ImageBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
File f = new File(Environment.getExternalStorageDirectory() + "/barcode1.png");
FileOutputStream fos = new FileOutputStream(f);
ImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
catch(Exception e)
{
e.printStackTrace();
}
}
This method generates and stores the barcode image in SDCard which m scanning using ZXing Barcode Scanner.
Barcode is successfully scanned when data is small. eg: 123.4|456.7
But if data is large, eg: 900000588548001100001305000000000207201512345.6|12345.7
It looks like some wrong barcode is generated and Scanner is not able to scan the generated barcode.
Thanks in advance for help.
Edit: Have added generated barcode images

You can upload the barcode image you produced to the ZXing Decoder Online to confirm if it is valid:
http://zxing.org/w/decode.jspx
There is no intrinsic limit to the length of a Code 128 barcode, and all the characters you have are valid.
Having said that, with Code 128A barcodes, having more than 20 characters encoded makes the resultant barcode very wide and hard to scan.
It is likely that the barcode is valid but the scanners camera is not able to get a clear enough picture of such a large barcode.
Take a look at this question for more information: Unable to scan Code 128
If possible, it would be recommended to use an alternative barcode format, such as QR code, which can store more data without increasing the barcode size.

https://play.google.com/store/apps/details?id=com.srowen.bs.android
android app scans perfectly. But while generating barcode make sure it's less width and height as possible, to easily fit to mobile camera to scan.
I regenerated barcode of CODE-128 for 900000588548001100001305000000000207201512345.6|12345.7 with just 300 and 150 it's able to scan, if it's not working for you then can scale up width and height.
Barcode generated: https://i.stack.imgur.com/UF0qJ.png
Screenshot after scanning

Related

Grayscale PNG writing from BufferedImage using PNGJ - hightest-level approach

I just want to, at first, use PNGJ at the highest possible level to write a grayscale PNG with bit-depth 8.
I am working from a BufferedImage. Here's a snippet of the code used:
BufferedImage scaledBI;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
...
ImageInfo imi = new ImageInfo(scaledBI.getWidth(), scaledBI.getHeight(), 8, false, true, false);
PngWriter pngw = new PngWriter(baos, imi);
pngw.setCompLevel(3);
DataBufferByte db =((DataBufferByte) scaledBI.getRaster().getDataBuffer());
byte[] dbbuf = db.getData();
ImageLineByte line = new ImageLineByte(imi, dbbuf);
for (int row = 0; row < imi.rows; row++) {
pngw.writeRow(line, row);
}
pngw.end();
return baos.toByteArray();
The original image is in j2k and is a palm print scan. The PNG looks similar to the background of the j2k with some vertical gray lines of different shades.
I tried the same buffered image data with ImageIO:
ImageIO.write(scaledBI, "png", baos);
and com.pngencoder.PngEncoder:
new PngEncoder().withBufferedImage(scaledBI).withCompressionLevel(3).toStream(baos);
which both render the image properly.
The long term aim is to improve on the speed offered by ImageIO and PngEncoder (which doesn't support grayscale).
I am stuck on just trying to run PNGJ with all default settings. I looked at the snippets in PNGJ Wiki Snippets and the test code but I couldn't find a simple example with grayscale without scanline or chunk manipulation.
Looking at the PNGJ code it seems like we are properly going through block deflation row after row. What am I missing here?
my problem sprung from my misunderstanding of what ImageLineByte stores, although as the name suggests it deals with a line, not the entire image data. I got confused by the fact that it references the image info. So my output was fine once I used ImageByteLine for each line:
for (int row = 0, offset = 0; row < imi.rows; row++) {
int newOffset = offset + imi.cols;
byte[] lineBuffer = Arrays.copyOfRange(dbbuf, offset, newOffset);
ImageLineByte line = new ImageLineByte(imi, lineBuffer);
pngw.writeRow(line, row);
offset = newOffset;
}
Sorry for the trouble.

Android: image saved using copyPixelsFromBuffer is distorted

I am trying to make an image processing program in Android Studio and I have a problem concerning how to save a Bitmap.
My problem is about saving an image which comes from a ByteBuffer.
To show it here, I have done this: I load an image in a ByteBuffer and I try to save it, rescaled to 1014x1163 pixels. And the image I get is distorted, messy.
For example, here is an image I load:
And here is what I get in the image I save:
Here is my code:
imageSize = (int) (bmWidth*bmHeight*4);
ByteBuffer pixelsArray = ByteBuffer.allocateDirect(imageSize);
ByteBuffer outputArray = ByteBuffer.allocateDirect(imageSize);
workingBitmap.copyPixelsToBuffer(pixelsArray);
workingBitmap.copyPixelsToBuffer(outputArray);
int thiswidth = workingBitmap.getWidth();
int thisheight = workingBitmap.getHeight();
Bitmap copiedBitmap = Bitmap.createScaledBitmap(workingBitmap, Width, Height, false);
int thiswidth2 = copiedBitmap.getWidth();
int thisheight2 = copiedBitmap.getHeight();
outputArray.rewind();
copiedBitmap.copyPixelsFromBuffer(outputArray);
SaveJPG(copiedBitmap);
The function SaveJPG works fine because if I call SaveJPG(workingBitmap) it saves a normal image.
Here is the code with variables values during debugging:
I am wondering if the problem comes from the fact that the output resolution is not a multiple of 4. That's mandatory in my program: the output image resolution can be of any value (odd or even).
I have tried many different things (copying workingBitmap and resizing the copy for example).
No success. I don't know what the cause of the problem is.
Does anyone have some source code which can save an image of any resolution, stored in a ByteBuffer ?
Thanks in advance.
Try this
try (FileOutputStream out = new FileOutputStream(yourFileName)) {
yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
e.printStackTrace();
}
Or use this
MediaStore.Images.Media.insertImage(getContentResolver(), yourbitmap,
"File name", "description of the image");
I have found the cause of the problem. It was simply due to a problem in the width and height of the input image: I was using the width and height of the View which displays the input bitmap, instead of using the bitmap's width and height.

pdf to .tiff conversion using java

I have created a web service that has a method which takes in a parameter of DataHandler. The purpose of this method is to read in what is sent over DataHandler and write it to a file(.tiff). When I pass in a .tiff file i can easily make a conversion but how should I make a conversion from a pdf file to a .tiff file using Java.
So if a user passes in a pdf file using DataHandler, how can I convert that to a .tiff file?
PDDocument doc = PDDocument.loadNonSeq(new File(filename), null);
boolean b;
List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
for (int p = 0; p < pages.size(); ++p)
{
// RGB image with 300 dpi
BufferedImage bim = pages.get(p).convertToImage(BufferedImage.TYPE_INT_RGB, 300);
// alternatively: B/W image with 300 dpi
bim = pages.get(p).convertToImage(BufferedImage.TYPE_BYTE_BINARY, 300);
// save as TIF with dpi in the metadata
// PDFBox will choose the best compression for you
// you need to add jai_imageio to your classpath for this to work
b = ImageIOUtil.writeImage(bim, "page-" + (p+1) + ".tif", 300);
if (!b)
{
// error handling
}
}
If your question is about converting to a multipage TIFF, please say so, I have a solution for this too.

Library to convert pdf to image

I have an Android application and I want to show up a PDF into it (without external applications). The only solution that I thought is to convert the pages of the PDF to images. Someone has experience with that issue? which library do you recommend me?
I tested the next libraries, but I have had troubles:
1) PdfRenderer library does not work with modern PDF
2) jPDFImages not work in Android (works in java desktop application)
Sorry for my English
I'm expanding on the accpeted answer and providing a complete solution.
Using this library: android-pdfview and the following code, you can reliably convert the PDF pages into images (JPG, PNG):
DecodeServiceBase decodeService = new DecodeServiceBase(new PdfContext());
decodeService.setContentResolver(mContext.getContentResolver());
// a bit long running
decodeService.open(Uri.fromFile(pdf));
int pageCount = decodeService.getPageCount();
for (int i = 0; i < pageCount; i++) {
PdfPage page = decodeService.getPage(i);
RectF rectF = new RectF(0, 0, 1, 1);
// do a fit center to 1920x1080
double scaleBy = Math.min(AndroidUtils.PHOTO_WIDTH_PIXELS / (double) page.getWidth(), //
AndroidUtils.PHOTO_HEIGHT_PIXELS / (double) page.getHeight());
int with = (int) (page.getWidth() * scaleBy);
int height = (int) (page.getHeight() * scaleBy);
// you can change these values as you to zoom in/out
// and even distort (scale without maintaining the aspect ratio)
// the resulting images
// Long running
Bitmap bitmap = page.renderBitmap(with, height, rectF);
try {
File outputFile = new File(mOutputDir, System.currentTimeMillis() + FileUtils.DOT_JPEG);
FileOutputStream outputStream = new FileOutputStream(outputFile);
// a bit long running
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
LogWrapper.fatalError(e);
}
}
You should do this work in the background i.e. by using an AsyncTask or something similar as quite a few methods take computation or IO time (I have marked them in comments).
You can use MuPDF. Here is a link that describes how to build MuPDF for android: http://mupdf.com/docs/how-to-build-mupdf-for-android
I recommend use this library, android-pdfview

Detect and decode multiple 2d (Datamatrix, QRcode) from an image

I'm working on a project which involves taking an image file as input on my desktop and then detecting and decoding all the barcodes present, both 1D and 2D.
I've been working with zxing and with the help of GenericMultipleBarcodeReader I was able to read multiple 1D barcodes from the image. However, it fails to detect 2D barcodes.
But if I crop the 2D barcode and input this cropped part separately it detects and decodes it without any problem.
So, if my image has 2 1D barcode and a 2D barcode my output consists of just the 2 1D barcodes decoded.
I also tried using ByQuadrantReader but that doesn't work either.
My code:
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result[] result;
HashMap<DecodeHintType,Object> hints = new HashMap<>();
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try
{
result = new GenericMultipleBarcodeReader(new MultiFormatReader()).decodeMultiple(bitmap, hints);
}
catch (ReaderException re)
{
return re.toString();
}
List<String> strings = new ArrayList<String>();
for (Result r: result)
{
strings.add(r.getText());
}
return String.valueOf(Arrays.toString(strings.toArray()));
Could anyone tell me a way to do this?
QR codes can be found anywhere in the image, but Data Matrix must be in the center of the image to be found. This is why it's working when you crop the image.

Categories

Resources