Android--解决图⽚保存到相册显⽰1970年1⽉1⽇8:00的问题t.Context;
t.Intent;
import android.database.Cursor;
aphics.Bitmap;
aphics.BitmapFactory;
aphics.Canvas;
aphics.Matrix;
aphics.Paint;
aphics.Rect;
dia.MediaScannerConnection;
import android.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
public class PictureUtils {
private static String TAG = SimpleName();
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) {
null官方更新地址LogUtils.dTag(TAG, "context 不能为null");
return;
}
.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("") || filePath.startsWith("")) {
Bitmap bmp = Glide.Instance())
.asBitmap()
.load(filePath)
.submit()
.get();
Instance(), bmp, filePath);
} else {
Bitmap bmp = BitmapFactory.decodeFile(filePath);
Instance(), 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) {
}
}
@Override
public void onNext(Boolean aBoolean) {
ToastUtils.showShort("图⽚已成功保存到系统相册^_^");
if (callBack != null) {
}
}
@Override
public void onError(Throwable e) {
if (mD != null) {
mD.dispose();
}
if (callBack != null) {
}
}
@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 ExternalStorageDirectory().getAbsolutePath(),
NetWorkConstants.FileKey.COMMONLIB_SHARE_CODE_DIR_NAME);// 获取⽂件存储路径if (!ists()) {
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, AbsolutePath());
AbsolutePath();
}
try {
FileOutputStream fos = new FileOutputStream(file);
bmppress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
// 插⼊图库
/**MediaStore.Images.Media
.ContentResolver(), AbsolutePath(), fileName,
String.valueOf(System.currentTimeMillis()));*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 最后通知图库更新
/**MediaScannerConnection.scanFile(context, new String[]{AbsolutePath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
}
});*/
try {
savePhotoToMedia(context, file, fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AbsolutePath();
}
/**
* 保存 Bitmap 到相册获得路径不传递⽂件名称⽤时间后缀
*/
public static String saveImageToGallery(Context context, Bitmap bmp) {
/
/ ⾸先保存图⽚
File appDir = ExternalFilesDir(
NetWorkConstants.FileKey.COMMONLIB_SHARE_CODE_DIR_NAME);// 获取⽂件存储路径if (appDir != null && !ists()) {
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, AbsolutePath());
AbsolutePath();
}
try {
FileOutputStream fos = new FileOutputStream(file);
bmppress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
// 插⼊图库
/**MediaStore.Images.Media
.ContentResolver(), AbsolutePath(), 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[]{AbsolutePath()}, 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("图⽚保存失败");
}
AbsolutePath();
}
public static Bitmap getBitmapFromView(Context context, View view) {
view.setDrawingCacheEnabled(true);
//启⽤DrawingCache并创建位图
view.buildDrawingCache();
//创建⼀个DrawingCache的拷贝,因为DrawingCache得到的位图在禁⽤后会被回收
Bitmap bitmap = DrawingCache());
//禁⽤DrawingCahce否则会影响性能
view.setDrawingCacheEnabled(false);
return bitmap;
}
//图⽚上绘制⽂字
public static Bitmap drawTextToBitmap(Bitmap bitmap, String text,
Paint paint, Rect bounds, int paddingLeft, int paddingTop) {
paint.setDither(true); // 获取跟清晰的图像采样
paint.setFilterBitmap(true);// 过滤⼀些
if (bitmapConfig == null) {
bitmapConfig = aphics.Bitmap.Config.ARGB_8888;
}
bitmap = py(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);
// 得到新的图⽚.
ateBitmap(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
.ContentResolver(), AbsolutePath(), fileName, null);
//        String uriString = MediaStore.Images.Media.ContentResolver(), 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 = ContentResolver().query(contentUri, proj, null, null, null);
if (cursor == null) {
return "";
}
int column_index = ColumnIndexOrThrow(MediaStore.Images.Media.DATA);        veToFirst();
String fileStr = String(column_index);
cursor.close();
return fileStr;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。