Android生成二維碼--保存和分享二維碼圖片

    以前寫過生成自定義二維碼的兩篇文章:《Android生成自定義二維碼》《Android生成二維碼–拍照或從相冊選取圖片》,下面就介紹一下Android應用內如何保存以及分享二維碼圖片。html

 

保存圖片android

     Adnroid中保存圖片能夠直接調用系統提供的插入圖庫的方法,或者指定存儲路徑。插入圖片後須要刷新系統圖庫。git

1.調用系統提供的插入圖庫方法github

//插入到系統圖庫
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");

 

   刷新圖庫微信

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

  這個方法沒法指定保存路徑和圖片名,並且刷新將掃描整個SD卡,用戶體驗很差,因此看下面這個方法。app

 

2.指定存儲路徑,更新圖庫spa

//發送廣播通知系統圖庫刷新數據
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

     這裏的uri是保存圖片的路徑,直接更新指定的路徑將不會掃描整個SD卡,節省資源的同時也能自定義保存路徑和文件名。因此須要先將圖片保存到指定路徑下,利用文件的IO流保存便可,以下:3d

/** * 保存圖片到指定路徑 * * @param context * @param bitmap 要保存的圖片 * @param fileName 自定義圖片名稱 * @return
 */
public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) { // 保存圖片至指定路徑
    String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode"; File appDir = new File(storePath); if (!appDir.exists()) { appDir.mkdir(); } File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); //經過io流的方式來壓縮保存圖片(80表明壓縮20%)
        boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.flush(); fos.close(); //發送廣播通知系統圖庫刷新數據
        Uri uri = Uri.fromFile(file); context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)); if (isSuccess) { return true; } else { return false; } } catch (IOException e) { e.printStackTrace(); } return false; }

 

  最後別忘了加入相應的權限,這裏涉及了敏感權限WRITE_EXTERNAL_STORAGE,須要動態申請,方法前面文章已經介紹過,這裏就再也不重複。code

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

分享圖片

  分享圖片或文字等簡單的內容,能夠直接使用系統提供的分享方法,無需集成第三方。以下orm

/** * 分享圖片(直接將bitamp轉換爲Uri) * @param bitmap */
private void shareImg(Bitmap bitmap){ Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null,null)); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/*");//設置分享內容的類型
 intent.putExtra(Intent.EXTRA_STREAM, uri); intent = Intent.createChooser(intent, "分享"); startActivity(intent); }

     因爲咱們獲取到的是圖片的Bitmap格式,爲了方便直接將其轉換爲Uri,可直接調用系統保存圖片的方法或者咱們上面自定義的圖片存儲方法,均可以獲得Uri。以後給startActivity傳入一個ACTION_SEND的Intent,設置分享類型便可。


效果圖

  以下圖,長按二維碼選擇存儲至手機後,提示存儲成功打開相冊便能看到圖片。點擊分享便可分享至微信等平臺。


       

       

 


源碼已更新至GitHub,地址:https://github.com/yangxch/GenerateQRCode

相關文章
相關標籤/搜索