Android 에서 ZXing 을 사용 하여 QR 코드 생 성(로고 그림 추가 지원)
우선 위의 효과 그림:
ZXing 관련 각종 파일 공식 다운로드 주소:https://github.com/zxing/zxing/releases
또는 여기 서 다운로드(본 프로젝트 에 사용 되 는 jar 패키지,버 전 번호:3.2.0):링크:http://pan.baidu.com/s/1pLqAR5x
1.QR 코드 생 성 도구 클래스
/**
*
*/
public class QRCodeUtil {
/**
* Bitmap
*
* @param content
* @param widthPix
* @param heightPix
* @param logoBm Logo ( null)
* @param filePath
* @return
*/
public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
try {
if (content == null || "".equals(content)) {
return false;
}
//
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 | IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 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;
}
}</encodehinttype,>
2.Activity 에서 의 사용:
/**
*
*/
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
final EditText contentET = (EditText) findViewById(R.id.create_qr_content);
//
final ImageView imageView = (ImageView) findViewById(R.id.create_qr_iv);
// Logo
final CheckBox addLogoCB = (CheckBox) findViewById(R.id.create_qr_addLogo);
Button createQrBtn = (Button) findViewById(R.id.create_qr_btn);
createQrBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String filePath = getFileRoot(MainActivity.this) + File.separator
+ "qr_" + System.currentTimeMillis() + ".jpg";
// , 、 ,
new Thread(new Runnable() {
@Override
public void run() {
boolean success = QRCodeUtil.createQRImage(contentET.getText().toString().trim(), 800, 800,
addLogoCB.isChecked() ? BitmapFactory.decodeResource(getResources(), R.mipmap.qr_logo) : null,
filePath);
if (success) {
runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
});
}
}
}).start();
}
});
}
//
private String getFileRoot(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File external = context.getExternalFilesDir(null);
if (external != null) {
return external.getAbsolutePath();
}
}
return context.getFilesDir().getAbsolutePath();
}
}
3.이 항목 에 그림 파일 저장
context.getExternalFilesDir(null)
목록 아래 의.공식 api 문서 에 따라 KitKat 부터(Android 4.4)파일 을 이 디 렉 터 리 에 저장 하면 SD 카드 읽 기와 쓰기 권한 이 필요 하지 않 습 니 다.그러나 테스트 를 통 해 홍 미 노트 와 매력 적 인 MX3(시스템 은 모두 안 드 로 이 드 4.4.4)에서 권한 이 필요 하지 않 은 것 으로 나 타 났 다.그러나 본인 의 화 웨 이 P6(Android 4.4.2)에서 권한 을 밝 혀 야 파일 을 성공 적 으로 저장 할 수 있 습 니 다.즉,manifest 에 다음 과 같은 내용 을 추가 해 야 합 니 다.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission></uses-permission>
이에 따라 개인 적 으로 필요 없 는 권한 이란 안 드 로 이 드 4.4.4 에서 시 작 된 것 으로 추정 된다.다음은 안 드 로 이 드 QR 코드 생 성 및 로고 추가 코드 를 공유 해 드 리 겠 습 니 다.
구체 적 인 코드 는 다음 과 같다.
@Override
public Bitmap generateBitmap(String content, int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//
hints.put(EncodeHintType.MARGIN, "1");//
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
@Override
public Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
int qrBitmapWidth = qrBitmap.getWidth();
int qrBitmapHeight = qrBitmap.getHeight();
int logoBitmapWidth = logoBitmap.getWidth();
int logoBitmapHeight = logoBitmap.getHeight();
Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(blankBitmap);
canvas.drawBitmap(qrBitmap, 0, 0, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
float scaleSize = 1.0f;
while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 3.5) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 3.5)) {
scaleSize *= 2;
}
float sx = 1.0f / scaleSize;
canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);
canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);
canvas.restore();
return blankBitmap;
}
자,코드 는 여기 서 끝 났 습 니 다.여러분 께 도움 이 되 셨 으 면 좋 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java에서 maven 기반 zxing QR코드 기능 구현maven에 필요한jar QR코드 생성: 위에서 말한 것은 여러분이 소개한 자바에서 마븐을 바탕으로 zxing QR코드 기능을 실현하는 것입니다. 여러분께 도움이 되었으면 합니다. 만약에 궁금한 것이 있으면 저에게 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.