Zxing扫描和生成二维码+butterknife8.0之后的引用+将drawable文件夹下的图片转换成Drawable
2016-11-10 16:34
731 查看
Zxing扫描和生成二维码+butterknife8.0之后的引用
**最近项目中用到二维码扫描和生成使用到了Zxing这里记录下来:先贴官方地址:**官网地址 开源中国 github.
项目下载地址:http://download.csdn.net/detail/u010023795/9679251
我这里只集成了扫码和二维码生成的功能这里主要用到的两个类:CaptureActivity 扫描和EncodingUtils生成:“
* /*
public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private SurfaceView scanPreview = null;
private RelativeLayout scanContainer;
private RelativeLayout scanCropView;
private ImageView scanLine;
private Rect mCropRect = null;
private boolean isHasSurface = false;
public Handler getHandler() {
return handler;
}
public CameraManager getCameraManager() {
return cameraManager;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_capture); scanPreview = (SurfaceView) findViewById(R.id.capture_preview); scanContainer = (RelativeLayout) findViewById(R.id.capture_container); scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view); scanLine = (ImageView) findViewById(R.id.capture_scan_line); inactivityTimer = new InactivityTimer(this); beepManager = new BeepManager(this); TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation .RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.9f); animation.setDuration(4500); animation.setRepeatCount(-1); animation.setRepeatMode(Animation.RESTART); scanLine.startAnimation(animation);
}
@Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is // necessary because we don't // want to open the camera driver and measure the screen size if we're // going to show the help on // first launch. That led to bugs where the scanning rectangle was the // wrong size and partially // off screen. cameraManager = new CameraManager(getApplication()); handler = null; if (isHasSurface) { // The activity was paused but not stopped, so the surface still // exists. Therefore // surfaceCreated() won't be called, so init the camera here. initCamera(scanPreview.getHolder()); } else { // Install the callback and wait for surfaceCreated() to init the // camera. scanPreview.getHolder().addCallback(this); } inactivityTimer.onResume();
}
@Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
beepManager.close();
cameraManager.closeDriver();
if (!isHasSurface) {
scanPreview.getHolder().removeCallback(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, “* WARNING * surfaceCreated() gave us a null surface!”);
}
if (!isHasSurface) {
isHasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
isHasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
A valid barcode has been found, so give an indication of success and show
the results.
*
@param rawResult The contents of the barcode.
@param bundle The extras
*/
public void handleDecode(Result rawResult, Bundle bundle) {
inactivityTimer.onActivity();
beepManager.playBeepSoundAndVibrate();
/*
这里是扫描成功之后返回数据给界面,需要返回的数据在这里添加
*/
Intent resultIntent = new Intent();
bundle.putInt(“width”, mCropRect.width()); //返回生成二维码扫描框的宽
bundle.putInt(“height”, mCropRect.height());//返回生成二维码扫描框的高
bundle.putString(“result”, rawResult.getText());//返回二维码的内容
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
CaptureActivity.this.finish();
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException(“No SurfaceHolder provided”);
}
if (cameraManager.isOpen()) {
Log.w(TAG, “initCamera() while already open – late SurfaceView callback?”);
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a
// RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
}
initCrop(); } catch (IOException ioe) { Log.w(TAG, ioe); displayFrameworkBugMessageAndExit(); } catch (RuntimeException e) { // Barcode Scanner has seen crashes in the wild of this variety: // java.?lang.?RuntimeException: Fail to connect to camera service Log.w(TAG, "Unexpected error initializing camera", e); displayFrameworkBugMessageAndExit(); }
}
private void displayFrameworkBugMessageAndExit() {
// camera error
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(“Camera error”);
builder.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
}
public Rect getCropRect() {
return mCropRect;
}
/**
初始化截取的矩形区域
*/
private void initCrop() {
int cameraWidth = cameraManager.getCameraResolution().y;
int cameraHeight = cameraManager.getCameraResolution().x;
/* 获取布局中扫描框的位置信息 /
int[] location = new int[2];
scanCropView.getLocationInWindow(location);
int cropLeft = location[0];
int cropTop = location[1] - getStatusBarHeight();
int cropWidth = scanCropView.getWidth();
int cropHeight = scanCropView.getHeight();
/* 获取布局容器的宽高 /
int containerWidth = scanContainer.getWidth();
int containerHeight = scanContainer.getHeight();
/* 计算最终截取的矩形的左上角顶点x坐标 /
int x = cropLeft * cameraWidth / containerWidth;
/* 计算最终截取的矩形的左上角顶点y坐标 /
int y = cropTop * cameraHeight / containerHeight;
/* 计算最终截取的矩形的宽度 /
int width = cropWidth * cameraWidth / containerWidth;
/* 计算最终截取的矩形的高度 /
int height = cropHeight * cameraHeight / containerHeight;
/* 生成最终的截取的矩形 /
mCropRect = new Rect(x, y, width + x, height + y);
}
private int getStatusBarHeight() {
try {
Class <> c = Class.forName(“com.android.internal.R$dimen”);//class<>里面为?
Object obj = c.newInstance();
Field field = c.getField(“status_bar_height”);
int x = Integer.parseInt(field.get(obj).toString());
return getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
下面是二维码生成工具类:
/**
二维码生成工具类
*/
public class EncodingUtils {
/**
创建二维码
*
@param content content
@param widthPix widthPix
@param heightPix heightPix
@param logoBm logoBm
@return 二维码
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || “”.equals(content)) {
return null;
}
// 配置参数
Map<> hints = new HashMap<>();//Map<>括号里应该是EncodeHintType, Object不知道为什么csdn里面这样直接这样写会造成下面的内容全部不显示
hints.put(EncodeHintType.CHARACTER_SET, “utf-8”);
// 容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
在二维码中间添加Logo图案
*/
private static Bitmap addLogo(Bitmap src, Bitmap logo) {
if (src == null) {
return null;
}
if (logo == null) {
return src;
}
//获取图片的宽高
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int logoWidth = logo.getWidth();
int logoHeight = logo.getHeight();
if (srcWidth == 0 || srcHeight == 0) {
return null;
}
if (logoWidth == 0 || logoHeight == 0) {
return src;
}
//logo大小为二维码整体大小的1/5
float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try {
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
} catch (Exception e) {
bitmap = null;
e.getStackTrace();
}
return bitmap;
}
}
这些类都是Zxing里面的,自己可以根据需要去封装。
封装好了类之后其实我们的调用就很简单了只需要写一个Activity。
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn_camer) Button btnCamer; @BindView(R.id.tv_result) TextView tvResult; @BindView(R.id.et_qr_string) EditText etQrString; @BindView(R.id.btn_creat) Button btnCreat; @BindView(R.id.if_logo) CheckBox ifLogo; @BindView(R.id.iamge_show) ImageView iamgeShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick({R.id.btn_camer, R.id.btn_creat, R.id.if_logo, R.id.iamge_show}) public void onClick(View view) { switch (view.getId()) { case R.id.btn_camer: startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class),0);//启动扫描界面 break; case R.id.btn_creat: String str = etQrString.getText().toString(); if (str.equals("")) { Toast.makeText(MainActivity.this, "不能为空", Toast.LENGTH_SHORT).show(); } else { // 位图 try { /** * 参数:1.文本 2 3.二维码的宽高 4.二维码中间的那个logo */ Bitmap bitma = BitmapFactory.decodeResource(getResources(), R.drawable.zaizai); Bitmap bitmap = EncodingUtils.createQRCode(str, 700, 700,bitma); // 设置图片 iamgeShow.setImageBitmap(bitmap); Toast.makeText(this,"55555"+str,Toast.LENGTH_SHORT).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } Toast.makeText(this,"55555",Toast.LENGTH_SHORT).show(); break; case R.id.if_logo: break; case R.id.iamge_show: break; } } /* 扫描成功之后返回二维码的信息在这里接收处理 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { String result = data.getExtras().getString("result"); Toast.makeText(this,result+"1",Toast.LENGTH_SHORT).show(); tvResult.setText(result); } }
}
二维码生成和扫描就这么写完了,但是在运行的时候竟然报控件空指针错误,就是说我的控件都是没有生成找不到的在运行的时候,但是我明明用了ButterKnife也添加进去了还可以自动生成,但是注解运行的时候就是没成功。后来找到了资料,原来在ButterKnife8.0以后引用发生了改变。现在必需多做几道程序下面请看图:
先把官网地址贴出来:http://jakewharton.github.io/butterknife/
github:https://github.com/JakeWharton/butterknife
接下来我们打开第一个gradle
添加classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’
第二步打开第二个gradle
apply plugin: ‘com.neenbedankt.android-apt’
compile ‘com.jakewharton:butterknife:8.4.0’
apt ‘com.jakewharton:butterknife-compiler:8.4.0’
最后注意添加的版本是不是一致,两个gradle中Butter Knife版本必须一致。最后重新 clean project就完成了。
参考:http://www.cnblogs.com/zzw1994/p/5197758.html
将drawable下的图片转换成bitmap
1、 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.xxx);
2、Resources r = this.getContext().getResources();
Inputstream is = r.openRawResource(R.drawable.xxx);
BitmapDrawable bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();
3、Resources r = this.getContext().getResources();
Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon);
Bitmap bmp = Bitmap.createBitmap( 300, 300, Config.ARGB_8888 );
将drawable下的图片转换成Drawable
Resources resources = mContext.getResources();
Drawable drawable = resources.getDrawable(R.drawable.a);
imageview.setBackground(drawable);
相关文章推荐
- 二维码生成、扫描、图片识别(Zxing)
- 基于ZXing Android实现生成二维码图片和相机扫描二维码图片即时解码的功能
- 使用zxing生成QRCode二维码,在Android的webview中调用条形码扫描(转)
- java zxing 生成带图片的二维码
- 使用Zxing生成二维码,以及保存到sdcard,图片变黑的问题
- ZXing拍摄代码扫描之后以区分一维码、二维码、其他代码
- 利用zxing开源工具生成二维码图片
- 关于drawable文件夹下面的图片不能动态在R文件下面生成资源ID
- Android 使用zxing包生成中间有logo的二维码图片
- Android平台利用ZXING生成二维码图片
- 用ZXing 生成条形码和二维码图片
- 使用zxing生成二维码图片,并解析
- Android平台利用ZXING生成二维码图片
- 【ZXing】Android使用zxing生成二维码图片
- Android平台利用ZXING生成二维码图片
- 使用python调用zxing库生成二维码图片
- 使用zxing生成嵌图片的二维码【java】
- iOS 条形码 二维码 的生成 和 扫描 zBarSDK zXing
- 用 zxing生成二维码图片
- (转载)java zxing 生成带图片的二维码