The URL is converted into a QR code.

Source: Internet
Author: User

The URL is converted into a QR code.

Reprinted please indicate the source: http://www.cnblogs.com/cnwutianhao/p/6685804.html

 

QR code has become an inaccessible product in our daily life. There will be QR codes on train tickets, scenic spots, and supermarket payments.

This article converts a URL into a QR code.

First look at the sample image

From the example, we can clearly see that the URL is converted into a QR code.

Follow me to implement this function.

 

Import open-source libraries provided by Google

compile 'com.google.zxing:core:3.3.0'

To explain the core part: QR Code Conversion

① Generate a QR code Bitmap

Public static boolean createQRImage (String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {try {if (content = null | "". equals (content) {return false;} // configure the Map parameter <EncodeHintType, Object> hints = new HashMap <> (); hints. put (EncodeHintType. CHARACTER_SET, "UTF-8"); // fault tolerance level hints. put (EncodeHintType. ERROR_CORRECTION, ErrorCorrectionLevel. h); // set the width of the blank margin hints. put (EncodeHintTy Pe. MARGIN, 2); // default is 4 // image data conversion, using the matrix conversion BitMatrix bitMatrix = new QRCodeWriter (). encode (content, BarcodeFormat. QR_CODE, widthPix, heightPix, hints); int [] pixels = new int [widthPix * heightPix]; // The following uses the QR code algorithm to generate images of QR codes one by one, // The two for loops are the results of the horizontal column scan of the image. for (int y = 0; y 

② Add a Logo in the middle of the QR code

Private static Bitmap addLogo (Bitmap src, Bitmap logo) {if (src = null) {return null;} if (logo = null) {return src ;} // obtain the image width and height 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 ;} // The logo size is 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 ;}

③ Create a directory for storing QR code files

private static 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();    }

④ Create a database tool class to store temporary data

Public class SPUtil {private static final String CONFIG = "config";/*** get the SharedPreferences Instance Object ** @ param fileName */private static SharedPreferences getSharedPreference (String fileName) {return QRCodeApplication. getInstance (). getSharedPreferences (fileName, Context. MODE_PRIVATE);}/*** save a value of the String type! */Public static void putString (String key, String value) {SharedPreferences. editor editor = getSharedPreference (CONFIG ). edit (); editor. putString (key, value ). apply ();}/*** get String value */public static String getString (String key, String defValue) {SharedPreferences sharedPreference = getSharedPreference (CONFIG); return sharedPreference. getString (key, defValue );}}

⑤ Display the QR code

Public static void showThreadImage (final Activity mContext, final String text, final ImageView imageView, final int centerPhoto) {String preContent = SPUtil. getString ("share_code_content", ""); if (text. equals (preContent) {String preFilePath = SPUtil. getString ("pai_code_filepath", ""); imageView. setImageBitmap (BitmapFactory. decodeFile (preFilePath);} else {SPUtil. putString ("pai_code_content", text); final String filePath = getFileRoot (mContext) + File. separator + "qr _" + System. currentTimeMillis () + ". jpg "; SPUtil. putString ("share_code_filePath", filePath); // when the QR code image is large, it may take a long time to generate and save the image. Therefore, the new Thread (new Runnable () {@ Override public void run () {boolean success = QRCodeUtil. createQRImage (text, 800,800, BitmapFactory. decodeResource (mContext. getResources (), centerPhoto), filePath); if (success) {mContext. runOnUiThread (new Runnable () {@ Override public void run () {imageView. setImageBitmap (BitmapFactory. decodeFile (filePath ));}});}}}). start ();}}

 

Construct a class for the input page and use the Bundle to pass the value through <key, value> (the value will be changed to the MVVM-DataBinding form later)

Public class ContentActivity extends AppCompatActivity implements View. onClickListener {private EditText etUrl; private Button btnConvert; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_content); initView ();} private void initView () {etUrl = (EditText) findViewById (R. id. et_url); btnConvert = (Button) findViewById (R. id. btn_convert); btnConvert. setOnClickListener (this) ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_convert: String str_url = "https: //" + etUrl. getText (). toString (); Bundle bundle = new Bundle (); bundle. putString ("url", str_url); // when the input box is empty, the user is prompted if (str_url.equals ("https: //") {Toast. makeText (getApplicationContext (), "the input box cannot be blank", Toast. LENGTH_SHORT ). show ();} else {Intent intent = new Intent (ContentActivity. this, MainActivity. class); intent. putExtras (bundle); startActivity (intent) ;}break; default: break ;}}}

 

Display the QR code image on the page (the MVVM-DataBinding format will be changed later)

public class MainActivity extends AppCompatActivity {    private ImageView iv;//    private String url = "http://weibo.com/cnwutianhao";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        String str_url = getIntent().getExtras().getString("url");        iv = (ImageView) findViewById(R.id.iv_qrcode);        QRCodeUtil.showThreadImage(this, str_url, iv, R.mipmap.ic_launcher);    }}

 

Layout File

① Enter the page (it will be changed to the DataBinding form later)

<? Xml version = "1.0" encoding = "UTF-8"?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical" android: padding = "10dp"> <EditText android: id = "@ + id/et_url" android: layout_width = "match_parent" android: layout_height = "50dp" android: layout_marginTop = "100dp" android: hint = "Enter the URL" android: inputType = "textUri"/> <Button android: id = "@ + id/btn_convert" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: Rule = "true" android: layout_centerHorizontal = "true" android: layout_marginBottom = "20dp" android: text = "convert to QR code"/> </RelativeLayout>

② QR code Display page

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.tnnowu.android.qrcode.MainActivity">    <ImageView        android:id="@+id/iv_qrcode"        android:layout_width="220dp"        android:layout_height="220dp"        android:layout_centerInParent="true"        android:layout_marginTop="40dp"        android:background="#FFFFFF" /></RelativeLayout>

 

The source code has been uploaded to Github. Welcome to Star and Fork. THX

Https://github.com/cnwutianhao/QRCode

 

Follow my Sina Weibo website to learn more about Android development!
Focus on science and technology critics, learn about science and technology, innovation, education, and maximize human wisdom and imagination!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.