Android 에서 QR 코드 생 성 방법(일반 QR 코드,중심 로고 QR 코드,스 캔 분석 QR 코드)
일단 저 희 는 이런 Zxing 가방 이 필요 해 요.이런 거.
다음은 자원 도입 이 필요 합 니 다.
1.drawable 에 그림 navbar.png 도입
2.layot 에 camera.xml,main.xml,qrcode 도입capture_page.xml
3.raw 폴 더 를 만 들 고 beep.ogg 스 캔 소 리 를 추가 합 니 다.
4.color.xml,copy ids.xml 를 values 디 렉 터 리 에 통합
파일 을 도입 한 후의 효과 도 는 이 렇 습 니 다.
다음은 QRcodeUtil 류 입 니 다.
package com.chinasie.barcodescanplugin;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
/**
* Created by HanWeijia on 2017/2/4.
*/
public class QRCodeUtil {
private static int QR_WIDTH = 300;
private static int QR_HEIGHT = 300;
/**
* Bitmap
*
* @param content
* @param widthPix
* @param heightPix
* @param logoBm Logo ( null)
* @param filePath
* @return
*/
public static Bitmap createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
try {
if (content == null || "".equals(content)) {
return null;
}
//
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//
// hints.put(EncodeHintType.MARGIN, 2); //default is 4
// ,
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;//!= null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
} 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;
}
/**
*
* ,
* @param url
*/
public static Bitmap createQRImage(String url)
{
try
{
// URL
if (url == null || "".equals(url) || url.length() < 1)
{
return null;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// ,
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
// , ,
// for
for (int y = 0; y < QR_HEIGHT; y++)
{
for (int x = 0; x < QR_WIDTH; x++)
{
if (bitMatrix.get(x, y))
{
pixels[y * QR_WIDTH + x] = 0xff000000;
}
else
{
pixels[y * QR_WIDTH + x] = 0xffffffff;
}
}
}
// , ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
return bitmap;
}
catch (WriterException e)
{
e.printStackTrace();
}
return null;
}
}
주석 은 이미 매우 명확 하 다.이 공구 류 는 내 가 더 이상 말 하지 않 고 내 려 와 서 호출 을 말 하 겠 다.물론 매우 간단 하 다.
package com.chinasie.barcodescanplugin;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.zxing.activity.CaptureActivity;
import java.io.File;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static String TAB = MainActivity.class.getSimpleName();
//
private EditText editText = null;
//
private Button btnScan = null;
//
private ImageView imageNormal = null;
//
private Button buttonNormal = null;
//
private Button buttonAndCenter = null;
//
private ImageView imageWithCenter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnScan:
try {
//
Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(openCameraIntent, 0);
}
catch (Exception ex){
Log.e(TAB,ex.getMessage());
ex.printStackTrace();
}
break;
case R.id.button:
// ImageView
imageNormal.setImageBitmap(QRCodeUtil.createQRImage("123456789"));
break;
case R.id.buttonAndCenter:
final String filePath = File.separator
+ "qr_" + System.currentTimeMillis() + ".jpg";
// , 、 ,
new Thread(new Runnable() {
@Override
public void run() {
final Bitmap success = QRCodeUtil.createQRImage("strUrl", 800,800,BitmapFactory.decodeResource(getResources(), R.drawable.gg),filePath);
if (success!=null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// imageWithCenter
imageWithCenter.setImageBitmap(success);
}
});
}
}
}).start();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// ( )
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString("result");
editText.setText(scanResult);
}
}
/**
* View
*/
private void initView(){
editText = (EditText)this.findViewById(R.id.editText);
imageWithCenter = (ImageView)findViewById(R.id.imageAndCenter);
imageNormal = (ImageView)this.findViewById(R.id.image) ;
btnScan = (Button)this.findViewById(R.id.btnScan);
buttonNormal = (Button)this.findViewById(R.id.button);
buttonAndCenter = (Button)findViewById(R.id.buttonAndCenter);
btnScan.setOnClickListener(this);
buttonNormal.setOnClickListener(this);
buttonAndCenter.setOnClickListener(this);
}
}
여기 도 말 이 많 을 뿐 입 니 다.담담 하 게 상술 한 자원 을 찾 지 못 하면 제 소스 코드 를 다운로드 할 수 있 습 니 다.안에 모두 있 습 니 다.클릭 하여 원본 다운로드
위 에서 기술 한 것 은 여러분 에 게 소개 한 안 드 로 이 드 의 QR 코드 생 성 방법(일반 QR 코드,센터 로고 QR 코드,그리고 스 캔 분석 QR 코드)입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.