Barbecue - Java Barcode
20:29
今天 jsptw 有人問到如何在 java 使用 barcode,
之前我都是使用 activx 元件來使用的.
不過有平台限制的問題. only for windows .
因此好奇查了 sourceforge, 原來有一個 BBQ ( Barbecue ) 就是處理 Java Barcode 的.

#BSD License#
Barbecue is an open-source, Java barcode library that provides the means to create barcodes for printing and display in Java applications. A number of barcode formats are supported and many more can be added via the flexible barcode API. Barcodes can be outputted to Graphics objects, or used as a Swing component, or written out as SVG. Please use the links on the left to find out more about Barbecue.
由他的簡介可以知道, 我們可以用在 Swing 也可以用 SVG 輸出.
web 使用, 其實他已經完成一個 Servlet - net.sourceforge.barbecue.BarcodeServlet ,
讓我們可以簡單地使用, 不需要花心思去真的實作他 !!
<img src="http://localhost:8080/barbecue/barcode?data=123545&height=50"/>
app 應用, 可以參考下面的 example code
import javax.swing.*;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.BarcodeImageHandler;import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;public class Example { public void usingBarbecueAsSwingComponent() {
JPanel panel = new JPanel(); // Always get a Barcode from the BarcodeFactory
Barcode barcode = null;
try {
barcode = BarcodeFactory.createCode128B("My Barcode");
} catch (BarcodeException e) {
// Error handling
} /* Because Barcode extends Component, you can use it just like any other
* Swing component. In this case, we can add it straight into a panel
* and it will be drawn and layed out according to the layout of the panel.
*/
panel.add(barcode);
} public void drawingBarcodeDirectToGraphics() throws BarcodeException {
// Always get a Barcode from the BarcodeFactory
Barcode barcode = BarcodeFactory.createCode128B("My Barcode"); // We are created an image from scratch here, but for printing in Java, your
// print renderer should have a Graphics internally anyway
BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_BYTE_GRAY);
// We need to cast the Graphics from the Image to a Graphics2D - this is OK
Graphics2D g = (Graphics2D) image.getGraphics(); // Barcode supports a direct draw method to Graphics2D that lets you position the
// barcode on the canvas
barcode.draw(g, 10, 56);
} public void outputtingBarcodeAsAJPEGImage() throws BarcodeException {
// Always get a Barcode from the BarcodeFactory
Barcode barcode = BarcodeFactory.createCode128B("My Barcode"); try {
// We need an output stream to write the image to...
FileOutputStream fos = new FileOutputStream("mybarcode.jpg"); // Let the barcode image handler do the hard work
BarcodeImageHandler.outputBarcodeAsJPEGImage(barcode, fos);
} catch (IOException e) {
// Error handling here
}
}
}