import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics... ...
import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.view.View; public class PictureUtils { private static String TAG = PictureUtils.class.getSimpleName(); private static int CODE_WIDTH = 60; private static int CODE_HEIGHT = 60; private PictureUtils() { } /** * 保存一張或者多張圖片到圖庫 */ public static void saveImageListToGallery(final BaseActivity context, final List<String> imgList, final OnSaveImgCallBack callBack) { if (context == null) { LogUtils.dTag(TAG, "context 不能為null"); return; } RxPermissionsUtils.getInstance() .requestPermission(context, RxPermissionsUtils.READ_AND_WRITE_PERMISSION, new RxPermissionsUtils.OnPermissionRequestCallBack() { @Override public void onSuccess() { if (imgList == null) { LogUtils.dTag(TAG, "圖片數組為 null"); return; } // 保存圖片到圖庫 saveImageListToGalleryPrivate(context, imgList, callBack); } @Override public void onFail() { ToastUtils.showShort("請在設置授予應用存儲許可權^_^"); PermissionUtils.launchAppDetailsSettings(); } }); } /** * 保存多張圖片 */ private static void saveImageListToGalleryPrivate(BaseActivity context, List<String> imgList, final OnSaveImgCallBack callBack) { Observable.just(imgList) .observeOn(Schedulers.io()) .flatMap(new Function<List<String>, ObservableSource<Boolean>>() { @Override public ObservableSource<Boolean> apply(List<String> strings) throws Exception { for (String filePath : strings) { if (filePath.startsWith("http://") || filePath.startsWith("https://")) { Bitmap bmp = Glide.with(BaseApplication.getInstance()) .asBitmap() .load(filePath) .submit() .get(); saveImageToGallery(BaseApplication.getInstance(), bmp, filePath); } else { Bitmap bmp = BitmapFactory.decodeFile(filePath); saveImageToGallery(BaseApplication.getInstance(), bmp, filePath); } } return Observable.just(true); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Boolean>() { Disposable mD; @Override public void onSubscribe(Disposable d) { mD = d; if (callBack != null) { callBack.onSaveStart(); } } @Override public void onNext(Boolean aBoolean) { ToastUtils.showShort("圖片已成功保存到系統相冊^_^"); if (callBack != null) { callBack.onSaveSuccess(); } } @Override public void onError(Throwable e) { if (mD != null) { mD.dispose(); } if (callBack != null) { callBack.onSaveFail(); } } @Override public void onComplete() { if (mD != null) { mD.dispose(); } } }); } /** * 保存 Bitmap 到相冊 獲得路徑 */ public static String saveImageToGallery(Context context, Bitmap bmp, String imageUrl) { if (!SDCardUtils.isSDCardEnableByEnvironment()) { LogUtils.dTag(TAG, "記憶體卡不可用"); return null; } // 首先保存圖片 File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), NetWorkConstants.FileKey.COMMONLIB_SHARE_CODE_DIR_NAME);// 獲取文件存儲路徑 if (!appDir.exists()) { boolean isCreate = appDir.mkdir(); if (!isCreate) { return null; } } // 創建文件 截取,取出名字 String url_truncated = String.valueOf(System.currentTimeMillis()); String fileName = "mryt_share_code" + "_" + url_truncated; File file = new File(appDir, fileName); FileUtils.deleteFile(file); if (FileUtils.isFileExists(file)) { LogUtils.dTag(TAG, file.getAbsolutePath()); return file.getAbsolutePath(); } try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); // 插入圖庫 /**MediaStore.Images.Media .insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, String.valueOf(System.currentTimeMillis()));*/ } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 最後通知圖庫更新 /**MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { } });*/ try { savePhotoToMedia(context, file, fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } return file.getAbsolutePath(); } /** * 保存 Bitmap 到相冊 獲得路徑 不傳遞文件名稱 用時間尾碼 */ public static String saveImageToGallery(Context context, Bitmap bmp) { // 首先保存圖片 File appDir = context.getExternalFilesDir( NetWorkConstants.FileKey.COMMONLIB_SHARE_CODE_DIR_NAME);// 獲取文件存儲路徑 if (appDir != null && !appDir.exists()) { boolean isCreate = appDir.mkdir(); if (!isCreate) { return null; } } if (!SDCardUtils.isSDCardEnableByEnvironment()) { LogUtils.dTag(TAG, "記憶體卡不可用"); return null; } // 創建文件 截取,取出名字 String url_truncated = String.valueOf(System.currentTimeMillis()); String fileName = "mryt_share_code" + "_" + url_truncated; File file = new File(appDir, fileName); if (FileUtils.isFileExists(file)) { LogUtils.dTag(TAG, file.getAbsolutePath()); return file.getAbsolutePath(); } try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); // 插入圖庫 /**MediaStore.Images.Media .insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, String.valueOf(System.currentTimeMillis()));*/ } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 最後通知圖庫更新 // context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); /**MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { } });*/ try { savePhotoToMedia(context, file, fileName); ToastUtils.showShort("圖片已成功保存到相冊"); } catch (FileNotFoundException e) { e.printStackTrace(); ToastUtils.showShort("圖片保存失敗"); } return file.getAbsolutePath(); } public static Bitmap getBitmapFromView(Context context, View view) { view.setDrawingCacheEnabled(true); //啟用DrawingCache並創建點陣圖 view.buildDrawingCache(); //創建一個DrawingCache的拷貝,因為DrawingCache得到的點陣圖在禁用後會被回收 Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); //禁用DrawingCahce否則會影響性能 view.setDrawingCacheEnabled(false); return bitmap; } //圖片上繪製文字 public static Bitmap drawTextToBitmap(Bitmap bitmap, String text, Paint paint, Rect bounds, int paddingLeft, int paddingTop) { android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig(); paint.setDither(true); // 獲取跟清晰的圖像採樣 paint.setFilterBitmap(true);// 過濾一些 if (bitmapConfig == null) { bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; } bitmap = bitmap.copy(bitmapConfig, true); Canvas canvas = new Canvas(bitmap); canvas.drawText(text, paddingLeft, paddingTop, paint); return bitmap; } public static Bitmap setImgSize(Bitmap bm, int newWidth, int newHeight) { // 獲得圖片的寬高. int width = bm.getWidth(); int height = bm.getHeight(); // 計算縮放比例. float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 取得想要縮放的matrix參數. Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的圖片. return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); } // 保存圖片的回調 public interface OnSaveImgCallBack { void onSaveStart(); void onSaveSuccess(); void onSaveFail(); } public static void savePhotoToMedia(Context context, File file, String fileName) throws FileNotFoundException { String uriString = MediaStore.Images.Media .insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null); // String uriString = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, null, null); File file1 = new File(getRealPathFromURI(Uri.parse(uriString), context)); updatePhotoMedia(file1, context); } //更新圖庫 private static void updatePhotoMedia(File file, Context context) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(file)); context.sendBroadcast(intent); } //得到絕對地址 private static String getRealPathFromURI(Uri contentUri, Context context) { String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (cursor == null) { return ""; } int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String fileStr = cursor.getString(column_index); cursor.close(); return fileStr; } }