Android產生帶圖片的二維碼

來源:互聯網
上載者:User

標籤:

一、問題描述

  在開發中需要將資訊轉換為二維碼儲存並要求帶有公司的logo,我們知道Google的Zxing開源項目就很好的協助我們實現條碼、二維碼的產生和解析,但帶有logo的官網並沒有提供demo,下面就通過執行個體看看如何?以及Zxing的使用。

二、案例介紹
1、案例運行效果

 

2、案例準備工作

  在項目中加入jar,只需加入core.jar

  Zxing項目地址:https://github.com/zxing/zxing/

三、Zxing主要組件
1、BarcodeFormat

  定義了不同的二進位編碼方式,取值如下

EAN_13條碼,共計13位代碼,比較常見,如商品上的封裝上的都是這種條碼

CODE_QR二維碼(矩陣碼),比條碼存在更多資訊,當下比較流行

CODE_128條碼 可表示可表示從 ASCII 0 到ASCII 127 共128個字元,用於企業管理,生產流程式控制制

CODE_39條碼,編製簡單只接受如下43個字元

2、MultiFormatWriter

  主要包含一個 encode()方法,可實現產生編碼(條形、二維碼)

  BitMatrix  encode(String contents, BarcodeFormat format, int width, int height,Hashtable hints)方法

  參數

contents:要編碼的內容

format:編碼格式(條形、二維)

width,height:產生碼的大小

hints:包含EncodeHintType(編碼提示類型)資訊的集合,主要設定字元編碼,比如支援漢字的utf-8,如下:

Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();

           hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");

  傳回值:BitMatrix 二維矩陣點

3、BitMatrix

  BitMatrix :表現為一個二維矩陣,x表示列的位置,y表示行的位置,循序從左上方開始,一列一列排列(先x後y)

  主要方法

getWidth():返回矩陣的寬度

getHeight():返回矩陣的高度

boolean get(x,y) :非常重要的方法,實現根據給定的x,y判斷該位置是否有黑塊

  在產生二維碼的應用中就是通過這個方法進行判斷,然後把有黑塊的點記錄下來,使用Bitmap的setPixels()方法產生圖形,詳解案例的createCode()方法中的代碼

四、完整代碼
public class MainActivity extends Activity {    private EditText etCompany;    private EditText etPhone;    private EditText etEmail;    private EditText etWeb;    private Bitmap logo;    private static final int IMAGE_HALFWIDTH = 40;//寬度值,影響中間圖片大小    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //獲得資源圖片,可改成擷取本地圖片或拍照擷取圖片        logo=BitmapFactory.decodeResource(super.getResources(),R.drawable.y014);        etCompany =(EditText) findViewById(R.id.etCompany);        etPhone=(EditText) findViewById(R.id.etPhone);        etEmail =(EditText) findViewById(R.id.etEmail);        etWeb =(EditText) findViewById(R.id.etWeb);         findViewById(R.id.but).setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                String company=etCompany.getText().toString().trim() ;                String phone =etPhone .getText().toString().trim() ;                 String email = etEmail.getText().toString().trim() ;                String web = etWeb.getText().toString().trim() ;                 //二維碼中包含的文本資訊                String contents= "BEGIN:VCARD\nVERSION:3.0\nORG:"+company+"\nTEL:"+phone+"\nURL:"+web+"\nEMAIL:"+email+"\nEND:VCARD";            try {                //調用方法createCode產生二維碼                Bitmap bm=createCode(contents,logo,BarcodeFormat.QR_CODE);                ImageView img=(ImageView)findViewById(R.id.imgCode) ;                //將二維碼在介面中顯示                img.setImageBitmap(bm);            } catch (WriterException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }                             }        });            }    /**     * 產生二維碼     * @param string 二維碼中包含的文本資訊     * @param mBitmap logo圖片     * @param format  編碼格式     * @return Bitmap 位元影像     * @throws WriterException     */    public Bitmap createCode(String string,Bitmap mBitmap, BarcodeFormat format)            throws WriterException {        Matrix m = new Matrix();        float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();        float sy = (float) 2 * IMAGE_HALFWIDTH                / mBitmap.getHeight();        m.setScale(sx, sy);//設定縮放資訊        //將logo圖片按martix設定的資訊縮放        mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,                mBitmap.getWidth(), mBitmap.getHeight(), m, false);        MultiFormatWriter writer = new MultiFormatWriter();        Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();        hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");//設定字元編碼        BitMatrix matrix = writer.encode(string, format, 400, 400, hst);//產生二維碼矩陣資訊        int width = matrix.getWidth();//矩陣高度        int height = matrix.getHeight();//矩陣寬度        int halfW = width / 2;        int halfH = height / 2;        int[] pixels = new int[width * height];//定義數組長度為矩陣高度*矩陣寬度,用於記錄矩陣中像素資訊        for (int y = 0; y < height; y++) {//從行開始迭代矩陣            for (int x = 0; x < width; x++) {//迭代列                if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH                        && y > halfH - IMAGE_HALFWIDTH                        && y < halfH + IMAGE_HALFWIDTH) {//該位置用於存放圖片資訊//記錄圖片每個像素資訊                    pixels[y * width + x] = mBitmap.getPixel(x - halfW                            + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);                } else {                    if (matrix.get(x, y)) {//如果有黑塊點,記錄資訊                        pixels[y * width + x] = 0xff000000;//記錄黑塊資訊                    }                }            }        }        Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_8888);        // 通過像素數組產生bitmap        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);        return bitmap;    }    }
View Code

  另,如果需要將將產生的二維碼儲存到磁碟中,可參考博文http://www.cnblogs.com/jerehedu/p/4464870.html中BitmapUtil的saveBmpToSd()方法

  

  想要進一步瞭解的同學,可以點擊查看原始碼,親自運行體驗!

 

傑瑞教育
出處:http://www.cnblogs.com/jerehedu/ 
本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。 

Android產生帶圖片的二維碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.