google.zxing barcode generator in iReport - java

I want put a barcode in my page and can preview it. The barcode generator is google.zxing and my reporting tool is iReport.
But i dont know, how to configure Image Expression and Expression Class of an image in iReport.

The two key ideas are first to write a bit of Java code to create the relevant image and then to design the report to reference this code appropriately. Perhaps the simplest way to generate the image is in a scriptlet like this:
package com.jaspersoft.alliances.mdahlman;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;
public class QRCodeScriptlet extends JRDefaultScriptlet {
public void afterDetailEval() throws JRScriptletException {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(getFieldValue("barcode_text").toString(), BarcodeFormat.QR_CODE, 256, 256);
this.setVariableValue("BarCodeImage", MatrixToImageWriter.toBufferedImage(matrix) );
} catch (WriterException e) {
e.printStackTrace();
}
}
}
That's full of hard-coded ugliness, but the key ideas are all shown. Then you need to define the report like this:
Sample query: select 'some text' as barcode_text
I included this only to reinforce the point that my scriptlet hard-codes the field name barcode_text. (This is bad.)
Variable: BarCodeImage of type java.awt.image.BufferedImage with calculation System.
This name is hard-coded in the scriptlet too. (This is equally bad.)
Add to iReport's classpath:
The compiled scriptlet .jar file
core.jar (from ZXing)
javase.jar (from ZXing)
Add an Image element to the report with Expression $V{BarCodeImage}.
The result is a happy happy QR-code in your generated JasperReport:
I recall a sample that I have seen which does things much more cleanly. It actually included a nice plug-in so you could easily install this functionality into iReport with minimal effort. If I can track that down, then I'll update this post. But until then this at least covers all of the critical points.

The image expression should return any subclass of java.awt.Image. The easiest way to achieve this is to use your own helper class to generate the Image. You can create a static method that generates a barcode from a Stringand call that method from IReport.
In the case of ZXing I don't know the method to use, but I can tell what I use as ImageExpression using the Barbecue library.
net.sourceforge.barbecue.BarcodeImageHandler.getImage(
MyBarcodeGenerator.getFromString($F{field})
MyBarcodeGenerator class contains the method getFromString(...) that returns a net.sourceforge.barbecue.Barcode in my case a net.sourceforge.barbecue.linear.code39.Code39Barcode
The Expression Class is ignored.
--Edited:
To encode an Image in zxing you should use MatrixToImageWriter
The following code will encode a QRCode into a BufferedImage which you can use in the Image Expression field:
MatrixToImageWriter.toBufferedImage(new QRCodeWriter().encode("BARCODE CONTENT", BarcodeFormat.QR_CODE, 400 /*Width*/, 400/*Height*/));

Related

Cannot inherit from final

I have a java image analysis program and am trying to get it to run on android. It starts like this (working on standard java):
import java.awt.image.BufferedImage;
public MaskImage(BufferedImage srcImage) {
super(srcImage.getWidth(), srcImage.getHeight(), srcImage.getType());
this.srcImage = srcImage;
this.height = srcImage.getHeight();
this.width = srcImage.getWidth();
}
When I try to get it working on android studio however I change bufferedimage to Bitmap, but still run into a couple of problems:
I cannot extend Bitmap in the same way I could BufferedImage
super(srcImage.getWidth(), srcImage.getHeight(), srcImage.getType());
this line runs into multiple issues, Says:
expected Parameters; actual: Arguments;
Thanks For any Help!
As you already know, Bitmap is final. By the very definition of final classes in Java, this means you cannot subclass it.
You will need to find an alternate strategy for accomplishing whatever you are trying to accomplish. Perhaps creating a class that wraps a Bitmap is one solution.

Referencing Pictures from resource folder in a Jar

I can't help it but think I've missed just the Thread to answer my question but I've been looking for a long time now and can't seem to find the help I need.
My problem is quite simple:
I've created a game (or rather I'm in the process of it) and I'm trying to add sprites (png files for the enemies and such) to it. Loading them in the IDE works just fine but when I create a jar file and try to open it, it simply says "A Java Exception has occurred". Further investigation revealed the problem is that it can't find the files I told it to load.
Through the threads I've read I gathered this much:
It's either that I'm not loading the images properly, meaning that I don't use the proper code for it, or
my MANIFEST.mf does not contain a "Class-Path" (meaning that the arguments are blank, which in fact they are)
Finding other code didn't work out for me. People suggested to use a ClassLoader which I could't manage to get working. Trying it out gave me nullpointer exceptions.
Trying to look into the latter didn't do much help, because I couldn't find any helping information, or I'm just not understanding anything.
package platformer.resources;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;
public class ImageLoader
{
static String spritePath = "src/platformer/resources/";
public static BufferedImage loadImage(String path)
{
BufferedImage img = null;
try{img= ImageIO.read(new File(spritePath+path));
}catch(IOException e){System.out.println("Couldn't load File: "+spritePath+path);}
return img;
}
public static BufferedImage flipImage(BufferedImage bufferedImage)
{
AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-bufferedImage.getWidth(null), 0);
AffineTransformOp op = new AffineTransformOp(tx,
AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
bufferedImage = op.filter(bufferedImage, null);
return bufferedImage;
}
}
This is the code I used so far.
Other classes would use "loadImage" or "flipImage" and in the IDE it works fine but as a .jar it fails to find the .png.
For example the class "platformer/entities/walker.class" would try to open the "Idle.png". In order to do that it uses the "loadImage("/entities/enemy/walker/Idle.png")" method. Note that in the method the actual path would end up being "src/platformer/resources/entities/enemy/walker/Idle.png".
Again, I'm terribly sorry if this has already been answered but I appreciate your help nonetheless.
Michael
When your files are inside a jar they can only be taken out as a resource stream so you will want to use something like:
ImageLoader.class.getResourceAsStream("nameoffile").
This is because a jar is actually a zipped up directory structure and files are not really files they are hidden amongst a compressed zip formatting as binary.

OpenCV Feature Detection always returns nothing

Background:
I'm working on creating an OpenCV Java command line app to tease out some information from some particle streak images. In particular, I would like to know the dimensions of the smallest possible bounding box which will fit over each particle streak. First I have to find the particles, so I use Simple Blob feature detection.
Code:
package com.bostonwalker;
import org.opencv.core.Mat;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.features2d.FeatureDetector;
import org.opencv.features2d.KeyPoint;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import java.util.List;
public class Main {
public static void main(String[] args)
{
System.loadLibrary("opencv_java247");
String sourcePath = "C:\\path_to_image\\05.png";
Mat srcImgMat = Highgui.imread(sourcePath);
if (srcImgMat == null)
{
System.out.println("Failed to load image at " + sourcePath);
return;
}
System.out.println("Loaded image at " + sourcePath);
MatOfKeyPoint matOfKeyPoints = new MatOfKeyPoint();
FeatureDetector blobDetector = FeatureDetector.create(FeatureDetector.SIMPLEBLOB);
blobDetector.detect(srcImgMat, matOfKeyPoints);
System.out.println("Detected " + matOfKeyPoints.size()+ " blobs in the image");
List<KeyPoint> keyPoints = matOfKeyPoints.toList();
}
}
Error:
Unfortunately, the returned matOfKeyPoints is always empty (size always equals 1x0). I have scoured the web, but opencv for desktop Java is not an extremely popular library, and my problem doesn't seem to be that common. I have tried using other feature detector algorithms just to see if I can return any key points whatsoever (the answer is no).
My gut instinct tells me that the color channel scheme of the image is not supported by the Simple Blob algorithm. I have exported the .png files from Photoshop as 8 bits/channel Grayscale and 8 bits/channel RGB Color. It's hard to know what's actually going on in the Highgui.imread() call, and what the Mat data actually looks like.
Questions:
What is causing the call to detect to return an empty matOfKeyPoints?
Is there an easier way to do the image processing I want done?
More information:
OpenCV version 2.4.7
Image included below
RESOLVED:
Found the problem. Namely, a small typo in the source path. It looks like Highgui.imread() returns an empty Mat when an incorrect source path is used, instead of returning null like I assumed it would.

Java Applet/Web Browser Issue

I am new to Java (and programming in general) so I thought that making a simple test case applet would help to form a basic understanding of the language.
So, I decided to make a basic applet that would display a green rectangle. The code looks like:
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
public class Box extends JApplet{
public void paint(Graphics page){
page.setColor(Color.green);
page.fillRect(0,150,400,50);
}
}
The HTML file (test.html) that I then embedded that into looks like:
<html>
<body>
<applet code="Box", height="200" width="400">
</applet>
</body>
</html>
I then compiled/saved the Java bit, and put the two into the same folder. However, when I attempt to view the html file, all I see is an "Error. Click for details" box. I tested this in both the most current version of Fire Fox and Opera, and too did I make sure that the Java plug-in was enabled and up to date for both.
So what exactly am I forgetting to do here?
It seems as if everything is close to OK.
Once the .class file is in the same folder as your HTML file it should come up. Your code might contain a typos (comma after "Box").
Example :
<Applet Code="MyApplet.class" width=200 Height=100>
See also :
http://www.echoecho.com/applets01.htm
#Juser1167589 I hope your not still having issues with this, but if you are, try going into your program files, delete the JAVA folder, then redownload java from the big red button on 'java.com'. If there is no JAVA folder then * FACEPALM * GO DOWNLOAD JAVA. another possible answer to why you were seeing the errors on the other sites is that they might not have the required resources to run it anymore.
Applets are not a good place to start.
They are a very old technology and really not very widely used compared to other parts of the Java technology stack.
If you're new to programming in general, I really wouldn't start with applets.
Instead, you should try learning basic programming and Java by building some simple console apps. I've added some general comments about how to do this. After your confidence rises, you can then start worrying about adding extra complexity, applets etc.
First of all download an IDE. Eclipse is one obvious choice (there are also NetBeans and IntelliJ). All modern developers work within an IDE - don't be tempted to try to muddle through without one.
Then, you should have a "scratchpad" - a class where you can try out some simple language features. Here's one which might be useful:
package scratch.misc;
public class ScratchImpl {
private static ScratchImpl instance = null;
// Constructor
public ScratchImpl() {
super();
}
/*
* This is where your actual code will go
*/
private void run() {
}
/**
* #param args
*/
public static void main(String[] args) {
instance = new ScratchImpl();
instance.run();
}
}
To use this, save this as a .java file. It can be a template for other simple experiments with Java. If you want to experiment with a language feature (inheritance, or polymorphism, or collections or whatever you want to learn) - then copy the template (use the copy and rename features inside your IDE, rather than manually copying the file and changing the type names) to a new name for your experiment.
You may also find some of my answer here to be useful.

JavaCV: cvLoadImage returns null no matter what I pass it

I'm on OS X 10.7.1. I've downloaded the latest JavaCV binaries, and built OpenCV from a current subversion checkout. The cvLoadImage() function returns null, no matter what I pass it. I have verified that I am passing it a valid path to a valid jpg image. Other JavaCV functions seem to return reasonable values, but since I can't load images, I can't really check.
I think I may have an error somewhere, but I'm not familiar with how JavaCV reports errors, so I can't check.
EDIT: I can verify that the overall JavaCV installation is valid and functioning, in that if I use Java's ImageIO to load an image, it works and I can subsequently operate on the loaded image, and save an image out (again, through ImageIO). SSCE follows:
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.BufferedImage;
import com.googlecode.javacv.cpp.*;
import com.googlecode.javacpp.Loader;
class ImgLoadTest {
public static void main(String[] args) {
//comment out EITHER the BufferedImage bit OR the cvLoadImage portion.
//works
BufferedImage img = ImageIO.read(new File(args[0]));
IplImage origImg = IplImage.createFrom(img);
//returns null
//IplImage origImg = cvLoadImage(args[0]);
System.out.println("origImg is" + origImg);
}
}
Since I can make it work via ImageIO, I'm not overly concerned about this bug anymore, but solving it may be of use to others working with JavaCV.
OpenCV only works well with ASCII filenames. If you have i18n characters in the path, it may very well choke. Also, at the moment, JavaCV maps all String objects to UTF-8, and it does not seem like Mac OS X uses UTF-8 by default.
So, if i18n is important to your application, keep on using ImageIO...

Categories