Posted on 2012-09-10 23:50
penngo 閱讀(6499)
評論(2) 編輯 收藏 所屬分類:
練手作品
要想攝像頭識別二維碼,需要兩個基本功能:1、從攝像頭獲取圖像,2、根據圖片解析出二維碼信息。在上一篇java攝像頭截圖已經實現了攝像頭截圖,只要再加上zxing(或其它能從圖片中解析二維碼的組件),就能從圖像中解析出二維碼,實現代碼如下:
1 package com.pengo.capture;
2
3 import javax.swing.JFrame;
4 import java.awt.BorderLayout;
5 import java.awt.Dimension;
6 import java.awt.Graphics2D;
7 import java.awt.image.BufferedImage;
8 import java.io.InputStream;
9 import javax.media.MediaLocator;
10 import javax.swing.JPanel;
11 import javazoom.jl.player.Player;
12 import com.google.zxing.BinaryBitmap;
13 import com.google.zxing.LuminanceSource;
14 import com.google.zxing.MultiFormatReader;
15 import com.google.zxing.Result;
16 import com.google.zxing.common.HybridBinarizer;
17
18 import net.sf.fmj.ui.application.CaptureDeviceBrowser;
19 import net.sf.fmj.ui.application.ContainerPlayer;
20 import net.sf.fmj.ui.application.PlayerPanelPrefs;
21 public class CameraFrame2 extends JFrame{
22 private static int num = 0;
23 public CameraFrame2() throws Exception{
24 this.setTitle("攝像頭截圖應用");
25 this.setSize(480, 500);
26 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 final JPanel cameraPanel = new JPanel();
28 this.getContentPane().setLayout(new BorderLayout());
29 this.getContentPane().add(cameraPanel, BorderLayout.CENTER);
30 ContainerPlayer containerPlayer = new ContainerPlayer(cameraPanel);
31 MediaLocator locator = CaptureDeviceBrowser.run(null); //彈出攝像頭設備選擇
32
33 PlayerPanelPrefs prefs = new PlayerPanelPrefs();
34 containerPlayer.setMediaLocation(locator.toExternalForm(), prefs.autoPlay);
35
36 new Thread() {
37 public void run() {
38 while (true) {
39 try {
40 Thread.sleep(1000);
41 Dimension imageSize = cameraPanel.getSize();
42 BufferedImage image = new BufferedImage(
43 imageSize.width, imageSize.height,
44 BufferedImage.TYPE_INT_ARGB);
45 Graphics2D g = image.createGraphics();
46 cameraPanel.paint(g);
47 g.dispose();
48 LuminanceSource source = new BufferedImageLuminanceSource(
49 image);
50 BinaryBitmap bitmap = new BinaryBitmap(
51 new HybridBinarizer(source));
52 Result result;
53 result = new MultiFormatReader().decode(bitmap);
54 System.out.println("二維碼====:" + result.getText());
55 InputStream is = CameraFrame.class.getClassLoader().getResourceAsStream("resource/beep.mp3");
56 Player player = new Player(is);
57 player.play();
58 } catch (Exception re) {
59 re.printStackTrace();
60 }
61 }
62 }
63 }.start();
64 }
65
66 public static void main(String[] args) throws Exception{
67 CameraFrame2 camera = new CameraFrame2();
68 camera.setVisible(true);
69 }
70 }
最后來張效果圖(本圖僅供參考)

要想識別效果好點,攝像頭像素最好500W以上,
活動二維碼簽到、物品掃描,只需扛臺手提,再加個高清攝像頭就行了。