Android实现支付宝个人收钱页面二维码图片保存功能

实现支付宝个人收钱页面二维码图片保存功能,效果如下:


Android实现支付宝个人收钱页面二维码图片保存功能_第1张图片
支付宝图片.jpg

思路

创建内容视图布局文件,将视图生成图片,然后再保存到图库中。
核心代码:

  • 布局文件(qrcode_page.xml):



    


    

    

    

  • 生成页面并保存至图库
    private void saveQrcodeToGallery() {
        //创建视图
        View qrcodeView = getLayoutInflater().inflate(R.layout.qrcode_page, null, false);
        ((ImageView)qrcodeView.findViewById(R.id.qrcodeImageView)).setImageDrawable(qrcodeImageView.getDrawable());

        //计算视图大小
        DisplayMetrics displayMetrics = SystemUtils.getWindowDisplayMetrics(mContext);
        final int width = displayMetrics.widthPixels;
        final int height = displayMetrics.heightPixels - SystemUtils.getStatusBarHeight(mContext) - SystemUtils.getActionBarHeight(mContext) - getResources().getDimensionPixelSize(R.dimen.default_bottom_bar_height);

        //将视图生成图片
        Bitmap image = SystemUtils.generateImageFromView(qrcodeView, width, height);

        //将图片保存到系统相册
        boolean isSuccess = SystemUtils.saveImageToGallery(MainActivity.this, image);
        image.recycle();
        if (isSuccess) {
            Toast.makeText(MainActivity.this, "已保存到系统相册!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "保存到系统相册失败!", Toast.LENGTH_SHORT).show();
        }
    }
  • SystemUtils.java的实现
package org.hjb.saveqrcodedemo;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by hejunbin on 2018/1/19.
 */

public class SystemUtils {

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        } else {
            result = context.getResources().getDimensionPixelSize(R.dimen.default_status_bar_height);
        }
        return result;
    }

    public static DisplayMetrics getWindowDisplayMetrics(Context context) {
        WindowManager wm = (android.view.WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    public static int getActionBarHeight(Context context) {
        int[] attrs = {android.R.attr.actionBarSize};
        TypedArray values = context.getTheme().obtainStyledAttributes(attrs);
        int actionBarHeight = values.getDimensionPixelSize(0, 0);
        values.recycle();

        if (actionBarHeight <= 0) {
            actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.default_action_bar_height);
        }

        return actionBarHeight;
    }


    public static Bitmap generateImageFromView(View view, int width, int height) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
        view.layout(0, 0, width, height);
        Bitmap image = Bitmap.createBitmap(view.getDrawingCache());
        view.destroyDrawingCache();

        return image;
    }


    /**
     * 将图片保存到系统相册
     *
     * @param context
     * @param bmp
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bmp) {

        String galleryPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_PICTURES;
        File galleryDir = new File(galleryPath);
        if (!galleryDir.exists()) {
            galleryDir.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(galleryPath, fileName);

        FileOutputStream fos = null;
        boolean isSuccess = false;

        try {
            fos = new FileOutputStream(file);
            isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return isSuccess;
    }
}
  • 二维码的生成采用三方库AwesomeQRCode实现,代码如下:
        new AwesomeQRCode.Renderer()
                .contents("HTTPS://QR.ALIPAY.COM/FKX08887CNJJPX3EOUGF7B")
                .size(getResources().getDimensionPixelSize(R.dimen.qrcode_size))//二维码的大小
                .margin(getResources().getDimensionPixelSize(R.dimen.qrcode_size_margin))//二维码边距即留白大小
                .dotScale(1)//点的伸缩比例
                .logoRadius(getResources().getDimensionPixelOffset(R.dimen.qrcode_size_logo_radius))//中心logo圆角大小
                .logo(BitmapFactory.decodeResource(getResources(), R.mipmap.icon))//中心logo
                .logoScale(0.25F)//logo占二维码的比例
                .renderAsync(new AwesomeQRCode.Callback() {
                    @Override
                    public void onRendered(AwesomeQRCode.Renderer renderer, final Bitmap bitmap) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                qrcodeImageView.setImageBitmap(bitmap);
                            }
                        });
                    }

                    @Override
                    public void onError(AwesomeQRCode.Renderer renderer, Exception e) {
                        e.printStackTrace();
                    }
                });

完整代码

https://github.com/hejunbinlan/SaveQRCodeDemo

你可能感兴趣的:(Android实现支付宝个人收钱页面二维码图片保存功能)