现在二维码使用的越来越多,做项目时难免会使用到,今天我向大家分享一下我自己使用的生产二维码和扫描二维码的方法。
一:通过谷歌提供的网络接口来生成二维码
这是一个通用的方法,只需要调用一下这个链接就能将你传过去的内容生成二维码返回给你,代码如下:
<?php
$content = '你要生成的内容'; generateQRfromGoogle($content);
function generateQRfromGoogle($content,$widhtHeight ='300',$EC_level='L',$margin='0') { $size=300; echo '<img src="http://chart.apis.google.com/chart?chs='.$widhtHeight.'x'.$widhtHeight.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$content.'" alt="QR code" widhtHeight="'.$size.'" widhtHeight="'.$size.'"/>'; } ?>
这个代码关键就在那个链接上,不管你使用的什么代码(我用的是php),只要将参数填写好然后获取这个链接的内容就能生成二维码,示例(http://chart.apis.google.com/chart?chs=85x85&cht=qr&chld=L|0&chl=http://jijie.cc/store/461):
在安卓中只需要内容和大小尺寸设置好,然后把它当作一个图片进行获取就能生成二维码(不会获取网络图片的同学请看我的上一篇博客)。
二:通过谷歌开源的扫描和生成二维码项目Zxing
生成二维码:
package zxing.standopen; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.Calendar; import zxing.moyan.index; import cn.domob.android.ads.DomobAdEventListener; import cn.domob.android.ads.DomobAdView; import cn.domob.android.ads.DomobInterstitialAd; import cn.domob.android.ads.DomobInterstitialAdListener; import cn.domob.android.ads.DomobAdManager.ErrorCode; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import ad.standopen.contact; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; public class Input extends Activity { private ImageView result=null; private Button save=null; private Button share=null; private Button back=null; Bitmap bmp=null; DomobInterstitialAd mInterstitialAd; RelativeLayout mAdContainer; DomobAdView mAdview320x50; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.input); save=(Button)findViewById(R.id.save); share=(Button)findViewById(R.id.share); result=(ImageView)findViewById(R.id.img); back=(Button)findViewById(R.id.back); String content=this.getIntent().getStringExtra("content"); try { bmp=createBitmap(Create2DCode(content)); } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } result.setImageBitmap(bmp); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, baos1); try { Writetemp(baos1.toByteArray()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //保存二维码 save.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, baos); if (mInterstitialAd.isInterstitialAdReady()){ mInterstitialAd.showInterstitialAd(Input.this); } else { Log.i("DomobSDKDemo", "Interstitial Ad is not ready"); mInterstitialAd.loadInterstitialAd(); } try { Write(baos.toByteArray()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); //分享二维码 share.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(Intent.ACTION_SEND); intent.setType("image/png"); File f = new File("/mnt/sdcard/zibuyu/temp/temp.jpg"); Uri u = Uri.fromFile(f); intent.putExtra(Intent.EXTRA_SUBJECT, "share"); intent.putExtra(Intent.EXTRA_TEXT,"二维码说说:一切尽在图片中!"); intent.putExtra(Intent.EXTRA_STREAM, u); intent.putExtra("sms_body","二维码说说:一切尽在图片中!"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(Intent.createChooser(intent, "分享图片到:")); } }); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); } //生成二维码,生成二维码返回BITMAP(重点) public Bitmap Create2DCode(String str) throws WriterException, UnsupportedEncodingException { //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败 BitMatrix matrix = new MultiFormatWriter().encode(new String(str.getBytes("GBK"),"ISO-8859-1"),BarcodeFormat.QR_CODE, 300, 300); int width = matrix.getWidth(); int height = matrix.getHeight(); //二维矩阵转为一维像素数组,也就是一直横着排了 int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if(matrix.get(x, y)){ pixels[y * width + x] = 0xff000000; } } } int[] colors={R.color.white}; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); //通过像素数组生成bitmap,具体参考api bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } //保存二维码 public void Write(byte []b) throws IOException { File cacheFile =null; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File sdCardDir = Environment.getExternalStorageDirectory(); long time=Calendar.getInstance().getTimeInMillis(); String fileName =time+".png"; File dir = new File(sdCardDir.getCanonicalPath() +"/zibuyu/"); if (!dir.exists()) { dir.mkdirs(); } cacheFile = new File(dir, fileName); } Toast toast = Toast.makeText(getApplicationContext(), "图片保存在了内存卡下zibuyu文件夹下,请查看!", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); LinearLayout toastView = (LinearLayout) toast.getView(); ImageView imageCodeProject = new ImageView(getApplicationContext()); imageCodeProject.setImageResource(R.drawable.fun); toastView.addView(imageCodeProject, 0); toast.show(); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(cacheFile)); bos.write(b,0,b.length); bos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void Writetemp(byte []b) throws IOException { File cacheFile =null; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File sdCardDir = Environment.getExternalStorageDirectory(); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String fileName ="temp.jpg"; File dir = new File(sdCardDir.getCanonicalPath() +"/zibuyu/temp"); if (!dir.exists()) { dir.mkdirs(); } cacheFile = new File(dir, fileName); } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(cacheFile)); bos.write(b,0,b.length); bos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Bitmap createBitmap( Bitmap src) { if( src == null ) { return null; } Paint paint=new Paint(); paint.setColor(Color.WHITE); paint.setAntiAlias(true); int w = 300; int h = 300; Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 ); Canvas cv = new Canvas( newb ); cv.drawColor(Color.WHITE); cv.drawBitmap(src, 0, 0, null ); cv.save( Canvas.ALL_SAVE_FLAG ); cv.restore();//存储 return newb; } }
三:扫描二维码
package zxing.standopen; import java.io.IOException; import java.util.Vector; import zxing.standopen.R; import zxing.standopen.result; import cn.domob.android.ads.DomobAdView; import com.google.zxing.BarcodeFormat; import com.google.zxing.Result; import com.zxing.camera.CameraManager; import com.zxing.decode.CaptureActivityHandler; import com.zxing.decode.InactivityTimer; import com.zxing.view.ViewfinderView; import android.app.Activity; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.view.SurfaceHolder; import android.view.View; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; import android.widget.Button; import android.widget.RelativeLayout; public class CaptureActivity extends Activity implements Callback { private CaptureActivityHandler handler; private ViewfinderView viewfinderView; private boolean hasSurface; private Vector<BarcodeFormat> decodeFormats; private String characterSet; private InactivityTimer inactivityTimer; private MediaPlayer mediaPlayer; private boolean playBeep; private static final float BEEP_VOLUME = 0.10f; private boolean vibrate; private Button back=null; RelativeLayout mAdContainer; DomobAdView mAdview320x50; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scanner); //��ʼ�� CameraManager back=(Button)findViewById(R.id.back); CameraManager.init(getApplication()); viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); hasSurface = false; inactivityTimer = new InactivityTimer(this); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); } @Override protected void onResume() { super.onResume(); SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (hasSurface) { initCamera(surfaceHolder); } else { surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } decodeFormats = null; characterSet = null; playBeep = true; AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE); if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { playBeep = false; } initBeepSound(); vibrate = true; } @Override protected void onPause() { super.onPause(); if (handler != null) { handler.quitSynchronously(); handler = null; } CameraManager.get().closeDriver(); } @Override protected void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } private void initCamera(SurfaceHolder surfaceHolder) { try { CameraManager.get().openDriver(surfaceHolder); } catch (IOException ioe) { return; } catch (RuntimeException e) { return; } if (handler == null) { handler = new CaptureActivityHandler(this, decodeFormats,"GBK"); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceCreated(SurfaceHolder holder) { if (!hasSurface) { hasSurface = true; initCamera(holder); } } public void surfaceDestroyed(SurfaceHolder holder) { hasSurface = false; } public ViewfinderView getViewfinderView() { return viewfinderView; } public Handler getHandler() { return handler; } public void drawViewfinder() { viewfinderView.drawViewfinder(); } public void handleDecode(Result obj, Bitmap barcode) { inactivityTimer.onActivity(); viewfinderView.drawResultBitmap(barcode); playBeepSoundAndVibrate(); // txtResult.setText(obj.getBarcodeFormat().toString() + ":" // + obj.getText()); // String info=""; // try { // info=new String(obj.getText().toString().getBytes("ISO-8859-1"),"utf-8"); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } Intent intent=new Intent(); intent.putExtra("info",obj.getText().toString()); intent.setClass(CaptureActivity.this,result.class); startActivity(intent); finish(); } private void initBeepSound() { if (playBeep && mediaPlayer == null) { // The volume on STREAM_SYSTEM is not adjustable, and users found it // too loud, // so we now play on the music stream. setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(beepListener); AssetFileDescriptor file = getResources().openRawResourceFd( R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException e) { mediaPlayer = null; } } } private static final long VIBRATE_DURATION = 200L; private void playBeepSoundAndVibrate() { if (playBeep && mediaPlayer != null) { mediaPlayer.start(); } if (vibrate) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(VIBRATE_DURATION); } } /** * When the beep has finished playing, rewind to queue up another one. */ private final OnCompletionListener beepListener = new OnCompletionListener() { public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.seekTo(0); } }; }
上图:
工程文件:https://github.com/yimengqingqiu/makeqr (github)
邮箱:standopen@foxmail.com (有什么疑问或者好的修改建议可以可以联系我)
package zxing.standopen;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import zxing.moyan.index;
import cn.domob.android.ads.DomobAdEventListener;
import cn.domob.android.ads.DomobAdView;
import cn.domob.android.ads.DomobInterstitialAd;
import cn.domob.android.ads.DomobInterstitialAdListener;
import cn.domob.android.ads.DomobAdManager.ErrorCode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import ad.standopen.contact;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class Input extends Activity {
private ImageView result=null;
private Button save=null;
private Button share=null;
private Button back=null;
Bitmap bmp=null;
DomobInterstitialAd mInterstitialAd;
RelativeLayout mAdContainer;
DomobAdView mAdview320x50;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.input);
save=(Button)findViewById(R.id.save);
share=(Button)findViewById(R.id.share);
result=(ImageView)findViewById(R.id.img);
back=(Button)findViewById(R.id.back);
String content=this.getIntent().getStringExtra("content");
try {
bmp=createBitmap(Create2DCode(content));
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setImageBitmap(bmp);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos1);
try {
Writetemp(baos1.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//保存二维码
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
if (mInterstitialAd.isInterstitialAdReady()){
mInterstitialAd.showInterstitialAd(Input.this);
} else {
Log.i("DomobSDKDemo", "Interstitial Ad is not ready");
mInterstitialAd.loadInterstitialAd();
}
try {
Write(baos.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//分享二维码
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
File f = new File("/mnt/sdcard/zibuyu/temp/temp.jpg");
Uri u = Uri.fromFile(f);
intent.putExtra(Intent.EXTRA_SUBJECT, "share");
intent.putExtra(Intent.EXTRA_TEXT,"二维码说说:一切尽在图片中!");
intent.putExtra(Intent.EXTRA_STREAM, u);
intent.putExtra("sms_body","二维码说说:一切尽在图片中!");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(intent, "分享图片到:"));
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
//生成二维码,生成二维码返回BITMAP(重点)
public Bitmap Create2DCode(String str) throws WriterException, UnsupportedEncodingException {
//生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
BitMatrix matrix = new MultiFormatWriter().encode(new String(str.getBytes("GBK"),"ISO-8859-1"),BarcodeFormat.QR_CODE, 300, 300);
int width = matrix.getWidth();
int height = matrix.getHeight();
//二维矩阵转为一维像素数组,也就是一直横着排了
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if(matrix.get(x, y)){
pixels[y * width + x] = 0xff000000;
}
}
}
int[] colors={R.color.white};
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
//通过像素数组生成bitmap,具体参考api
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
//保存二维码
public void Write(byte []b) throws IOException
{
File cacheFile =null;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();
long time=Calendar.getInstance().getTimeInMillis();
String fileName =time+".png";
File dir = new File(sdCardDir.getCanonicalPath()
+"/zibuyu/");
if (!dir.exists()) {
dir.mkdirs();
}
cacheFile = new File(dir, fileName);
}
Toast toast = Toast.makeText(getApplicationContext(),
"图片保存在了内存卡下zibuyu文件夹下,请查看!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageCodeProject = new ImageView(getApplicationContext());
imageCodeProject.setImageResource(R.drawable.fun);
toastView.addView(imageCodeProject, 0);
toast.show();
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
bos.write(b,0,b.length);
bos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Writetemp(byte []b) throws IOException
{
File cacheFile =null;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String fileName ="temp.jpg";
File dir = new File(sdCardDir.getCanonicalPath()
+"/zibuyu/temp");
if (!dir.exists()) {
dir.mkdirs();
}
cacheFile = new File(dir, fileName);
}
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
bos.write(b,0,b.length);
bos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Bitmap createBitmap( Bitmap src)
{
if( src == null )
{
return null;
}
Paint paint=new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
int w = 300;
int h = 300;
Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );
Canvas cv = new Canvas( newb );
cv.drawColor(Color.WHITE);
cv.drawBitmap(src, 0, 0, null );
cv.save( Canvas.ALL_SAVE_FLAG );
cv.restore();//存储
return newb;
}
}