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;
}
}