Android 에서 QR 코드 생 성 방법(일반 QR 코드,중심 로고 QR 코드,스 캔 분석 QR 코드)

우선 Google 오픈 소스 프레임 워 크 Zxing 을 사용 하고 있 음 을 알려 드 립 니 다.구현 할 기능 은 세 가지 입 니 다.일반 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 코드)입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기