二维码在哪里 采样二维码在哪里
大家对二维码司空见惯了吧,二维码从哪里来,如何识别,请看代码吧。
使用zxing.jar库文件,可以做其他很多应用。
1 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.orbbec.colorViewer"
android:versionCode="1"
android:versionName="1.0.8" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.orbbec.colorViewer.MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
展开全文
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
</manifest>
2 MainActivity.java
package com.orbbec.colorViewer;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Hashtable;
import org.openni.ImageMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.orbbec.NativeNI.NativeMethod;
import com.orbbec.UVC.LiveCamera;
import com.orbbec.UVC.LiveStreamProcessor;
import com.orbbec.astrakernel.AstraContext;
import com.orbbec.astrakernel.DepthData;
import com.orbbec.astrakernel.PermissionCallbacks;
import com.orbbec.astrastartlibs.RGBData;
import com.orbbec.utils.GlobalDef;
public class MainActivity extends Activity implements SurfaceHolder.Callback {
String TAG = "深大云网络";
String VERSION = "1.0.9";
int m_versionInt;
AstraContext m_xc;
RGBData m_rgbdata;
DepthData mDepthData;
boolean m_bexit = false; // 控制视频绘制的标志
int m_Width;
int m_Height;
Bitmap m_colorBitmap;
private byte[] m_pixels;
private int[] m_rgbIntData;
/* Live UVC Camera */
WindowManager mWm;
private LiveCamera liveCamera;
LiveStreamProcessor processor = new LiveStreamProcessor();
private SurfaceView mSvPreview;
private SurfaceHolder mSurfaceHolder;
final int PREVIEW_WIDTH = 80;
final int PREVIEW_HEIGHT = 60;
private HomeKeyListener mHomeListener;
private TextView hintText;
private boolean isDialogShow = false; // 判断对话框是否弹出来的标志
private Thread mCameraThread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Log.d(TAG, "before initUVCCamera!!");
initUVCCamera();
Log.d(TAG, "after initUVCCamera!!");
Looper.loop();
}
});
private PermissionCallbacks m_callbacks = new PermissionCallbacks() {
@Override
public void onDevicePermissionGranted() {
try {
mDepthData = new DepthData(m_xc);
mDepthData.setMapOutputMode(GlobalDef.RES_DEPTH_WIDTH,
GlobalDef.RES_DEPTH_HEIGHT, 30);
m_rgbdata = new RGBData(m_xc);
m_rgbdata.setMapOutputMode(GlobalDef.RES_COLOR_WIDTH,
GlobalDef.RES_COLOR_HEIGHT, 30);
m_rgbdata.getGenerator().getMirrorCapability().setMirror(false);// true,false
m_Width = m_rgbdata.GetImageMap().getXRes();
m_Height = m_rgbdata.GetImageMap().getYRes();
// Log.i(TAG,"width = " + m_Width);
// Log.i(TAG,"m_Height = " + m_Height);
m_rgbIntData = new int[GlobalDef.RES_DISPLAY_WIDTH
* GlobalDef.RES_DISPLAY_HEIGHT];
m_colorBitmap = Bitmap.createBitmap(
GlobalDef.RES_DISPLAY_WIDTH,
GlobalDef.RES_DISPLAY_HEIGHT, Bitmap.Config.ARGB_8888);
} catch (Exception e) {
Log.w(TAG, "Exception: " + e.getMessage());
}
Log.i(TAG, "start xc!");
try {
m_xc.start(); // 开始生成设定好的数据
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (GlobalDef.USE_UVC) {
Log.d(TAG, "start Thread of UVC camera!!");
/*mCameraThread.start();
Message msg = new Message();
msg.what = 1;
// 1.5s delay
handler.sendMessageDelayed(msg, 3000);*/
} else {
Message msg = new Message();
msg.what = 1;
// 1.5s delay
handler.sendMessageDelayed(msg, 500);
}
}
@Override
public void onDevicePermissionDenied() {
Toast.makeText(MainActivity.this, "onDevicePermissionDenied ",
Toast.LENGTH_SHORT).show();
}
};
private Handler handler = new Handler() {
@Override
/* 褰撴湁娑堟伅鍙戦�鍑烘潵鐨勬椂鍊欏氨鎵цHandler鐨勮繖涓柟娉� */
public void handleMessage(Message msg) {
super.handleMessage(msg);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.RGBLayout);
// Add the adView to it
layout.addView(new ColorView(MainActivity.this));
Log.i(TAG, "Create ColovrView!");
}
};
private Handler updateHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
AlertDialog.Builder budler = new AlertDialog.Builder(
MainActivity.this);
budler.setTitle("恭喜您,获取二维码信息成功!");
budler.setMessage((String) msg.obj);
budler.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
isDialogShow = false;
}
});
budler.show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "obColor version = " + VERSION);
m_versionInt = Build.VERSION.SDK_INT;
mWm = (WindowManager) getSystemService(WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
mWm.getDefaultDisplay().getMetrics(dm);
try {
m_xc = new AstraContext(this, m_callbacks);
GlobalDef.USE_UVC = m_xc.IsUVC();
if (GlobalDef.USE_UVC) {
Log.i(TAG, "Astra Pro * Detected!");
} else {
Log.i(TAG, "Astra * Detected!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
registerHomeListener();
}
private void initUVCCamera() {
// LiveStreamProcessor processor = new LiveStreamProcessor();
int previewWidth = processor.getSupportPreviewWidth();
int previewHeight = processor.getSupportPreviewHeight();
Log.i(TAG, "previewWidth = " + previewWidth);
Log.i(TAG, "previewHeight = " + previewHeight);
liveCamera = new LiveCamera();
int rc = liveCamera.init(GlobalDef.RES_UVC_WIDTH,
GlobalDef.RES_UVC_HEIGHT, 30, processor, processor.getBuffer());
if (rc < 0) {
dialog();
return;
}
mSvPreview = new SurfaceView(this);
mSurfaceHolder = mSvPreview.getHolder();
mSurfaceHolder.addCallback(this);
createDisplayView();
}
private void createDisplayView() {
// Log.e(TAG, "createView");
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
wmParams.format = PixelFormat.RGBA_8888;
wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wmParams.gravity = Gravity.RIGHT | Gravity.TOP;
wmParams.width = PREVIEW_WIDTH;
wmParams.height = PREVIEW_HEIGHT;
Log.d(TAG, "top color width = " + wmParams.width);
Log.d(TAG, "top color height = " + wmParams.height);
mWm.addView(mSvPreview, wmParams);
mSvPreview.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
}
@Override
protected void onPause() {
Log.w(TAG, "Activity onPause");
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
protected void onDestroy() {
if (mHomeListener != null) {
mHomeListener.stopWatch();
}
if (m_rgbdata != null) {
m_rgbdata.Close();
}
if (mDepthData != null) {
mDepthData.Close();
}
if (liveCamera != null) {
Log.d(TAG, "liveCamera.terminate()!!!");
liveCamera.terminate();
}
if (m_xc != null) {
m_xc.Close();
}
unRegisterHomeListener();
Log.i(TAG, "Activity onDestroy !");
System.exit(0);
super.onDestroy();
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// Log.e(TAG, "surfaceChanged");
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
Log.e(TAG, "surfaceCreated");
if (GlobalDef.USE_UVC) {
liveCamera.setPreviewDisplay(mSurfaceHolder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// Log.e(TAG, "surfaceDestroyed");
}
public class ColorView extends SurfaceView implements Callback, Runnable {
private SurfaceHolder m_holder;
private Canvas m_canvas;
private Paint m_paint;
Thread m_surfaceThread;
public ColorView(Context context) {
super(context);
m_holder = this.getHolder();
m_holder.addCallback(this);
m_paint = new Paint();
m_paint.setColor(Color.WHITE);
LinearLayout.LayoutParams layParams = new LinearLayout.LayoutParams(
m_Width, m_Height);
setLayoutParams(layParams);
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
int arg3) {
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
if (m_surfaceThread == null || m_surfaceThread != null
&& !m_surfaceThread.isAlive()) {
m_bexit = false;
m_surfaceThread = new Thread(this);
m_surfaceThread.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.i(TAG, "ColorView onDestory!!");
m_bexit = true;
m_surfaceThread = null;
}
@Override
public void run() {
while (!m_bexit) {
try {
m_xc.waitforupdate(); // 更新数据
m_canvas = m_holder.lockCanvas();
if (m_canvas != null) {
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
m_canvas.drawPaint(paint);
if (!GlobalDef.USE_UVC) {
ImageMap imageMap = m_rgbdata.GetImageMap();
ByteBuffer byteBufferTemp = imageMap
.createByteBuffer();
m_pixels = byteBufferTemp.array();
NativeMethod.GetRGBData(m_pixels, m_rgbIntData,
m_Width, m_Height, m_versionInt);
} else {
if (processor.getRealTimeData() == null
|| processor.getRealTimeData().length <= 0) {
continue;
}
// Log.d(TAG,"Get Buffer from liveCamera!");
NativeMethod.NV21ToMirrorRGBA(
processor.getRealTimeData(), m_rgbIntData,
GlobalDef.RES_UVC_WIDTH,
GlobalDef.RES_UVC_HEIGHT);
// Log.d(TAG,"Get Buffer from liveCamera!!!!!");
}
m_colorBitmap.setPixels(m_rgbIntData, 0, m_Width, 0, 0,
m_Width, m_Height);
if (m_colorBitmap != null) {
m_canvas.drawBitmap(m_colorBitmap, 0, 0, null);
/*
* 获取帧图片中的二维码并且显示出来**********************************
* ****************************
*/
Result result = scanningImage(m_colorBitmap);
// String result = decode(photo_path);
if (result == null) {
Log.i("123", "二维码图片格式不正确");
} else {
Log.i("123result", result.toString());
// 数据返回
final String recode = recode(result.toString());
if(!isDialogShow){
Message msg = Message.obtain();
msg.obj = recode;
updateHandler.sendMessage(msg);
isDialogShow = true;
}
}
/**********************************************************************************************/
}
m_holder.unlockCanvasAndPost(m_canvas);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
//
/**
* 解析部分图片
*
* @author jcq
* @param Bitmap 扫码获取到的bitmap
* @return 二维码解析出来的字符串结果
*/
protected Result scanningImage(Bitmap scanBitmap) {
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码
RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
return reader.decode(bitmap1, hints);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return null;
}
/**
* 中文乱码,能解决大部分的中文乱码
*
* @author jcq
* @return 解码后的字符串
*/
private String recode(String str) {
String formart = "";
try {
boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
.canEncode(str);
if (ISO) {
formart = new String(str.getBytes("ISO-8859-1"), "GB2312");
Log.i("1234 ISO8859-1", formart);
} else {
formart = str;
Log.i("1234 stringExtra", str);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formart;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected void dialog() {
AlertDialog.Builder builder = new Builder(this);
builder.setMessage(R.string.uvc_open_again);
builder.setTitle(R.string.warning);
builder.setPositiveButton(R.string.confirm, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
builder.create().show();
}
/**
* 注册Home键的监听
*/
private void registerHomeListener() {
mHomeListener = new HomeKeyListener(this);
mHomeListener
.setOnHomePressedListener(new HomeKeyListener.OnHomePressedListener() {
@Override
public void onHomePressed() {
// TODO 进行点击Home键的处理
finish();
}
@Override
public void onHomeLongPressed() {
// TODO 进行长按Home键的处理
}
});
mHomeListener.startWatch();
}
private void unRegisterHomeListener() {
if (mHomeListener != null) {
mHomeListener.stopWatch();
}
}
}
3 RGBLuminanceSource.java
package com.orbbec.colorViewer;
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.FileNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.google.zxing.LuminanceSource;
/**
* This class is used to help decode images from files which arrive as RGB data
* from Android bitmaps. It does not support cropping or rotation.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class RGBLuminanceSource extends LuminanceSource {
private final byte[] luminances;
public RGBLuminanceSource(String path) throws FileNotFoundException {
this(loadBitmap(path));
}
public RGBLuminanceSource(Bitmap bitmap) {
super(bitmap.getWidth(), bitmap.getHeight());
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
// In order to measure pure decoding speed, we convert the entire image
// to a greyscale array
// up front, which is the same as the Y channel of the
// YUVLuminanceSource in the real app.
luminances = new byte[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
int pixel = pixels[offset + x];
int r = (pixel >> 16) & 0xff;
int g = (pixel >> 8) & 0xff;
int b = pixel & 0xff;
if (r == g && g == b) {
// Image is already greyscale, so pick any channel.
luminances[offset + x] = (byte) r;
} else {
// Calculate luminance cheaply, favoring green.
luminances[offset + x] = (byte) ((r + g + g + b) >> 2);
}
}
}
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException(
"Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
System.arraycopy(luminances, y * width, row, 0, width);
return row;
}
// Since this class does not support cropping, the underlying byte array
// already contains
// exactly what the caller is asking for, so give it to them without a copy.
@Override
public byte[] getMatrix() {
return luminances;
}
private static Bitmap loadBitmap(String path) throws FileNotFoundException {
Bitmap bitmap = BitmapFactory.decodeFile(path);
if (bitmap == null) {
throw new FileNotFoundException("Couldn't open " + path);
}
return bitmap;
}
}
www.shendayun.com www9813cn.com 深大云网络(深圳)有限公司是深圳南山科技园注册成立的一家高科技公司。公司产品主要是软件开发、软件销售、网络开发、网络推广、网络营销、互联网系统解决方案,微信二次开发等。18664905986