/**
* 將Bitmap圖片保存到本地相冊
*/
public static void savePhotoToGallery(final Context context, final Bitmap bitmap) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AndPermission.with((Activity) context)
.requestCode(200)
.permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.start();
}
if (bitmap == null) {
ToastUtil.showCenterToast(context, "未獲取到圖片");
return;
}
new Thread(new Runnable() {
@Override
public void run() {
// 其次把文件插入到系統(tǒng)圖庫
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap,
fileName, "測試 圖集"); // 名字和描述沒用,系統(tǒng)會自動更改
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showCenterToast(context, "圖片保存至相冊");
}
});
} catch (Exception e) {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showCenterToast(context, "圖片保存失敗");
}
});
LogUtils.e("圖片保存異常:", e);
}
}
}).start();
}
/**
* 將圖片保存到本地相冊
*
*/
public static void savePhotoToGallery(final Context context, final String imgUrl) {
if (TextUtils.isEmpty(imgUrl)) {
ToastUtil.showCenterToast(context,"未獲取到圖片");
return;
}
new Thread(new Runnable() {
@Override
public void run() {
String fileName = "test_" + System.currentTimeMillis() + ".jpg";
String sdCardDir = SDCardUtils.getDiskDir() + "DCIM/";
File appDir = new File(sdCardDir, "text");
if (!appDir.exists()) {
appDir.mkdir();
}
File f = new File(appDir, fileName);
try {
// 保存圖片
URL url = new URL(imgUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(1000 * 6);
if (con.getResponseCode() == 200) {
InputStream inputStream = con.getInputStream();
byte[] b = FileUtils.getBytes(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(b);
fileOutputStream.close();
} else {
ToastUtil.showCenterToast(context,"圖片保存失敗");
return;
}
//把文件插入到系統(tǒng)圖庫
MediaStore.Images.Media.insertImage(context.getContentResolver(),
f.getAbsolutePath(), fileName, null);
// 通知圖庫更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(f.getPath()))));
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showCenterToast(context,"圖片保存至相冊");
}
});
} catch (Exception e) {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showCenterToast(context,"圖片保存失敗");
}
});
LogUtils.e("圖片保存異常:", e);
}
}
}).start();
}
其中的getBytes方法如下:
/**
* 將InputStream楷力,轉換為字節(jié)
*/
public static byte[] getBytes(InputStream inputStream) throws Exception {
byte[] b = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = -1;
while ((len = inputStream.read(b)) != -1) {
byteArrayOutputStream.write(b, 0, len);
}
byteArrayOutputStream.close();
inputStream.close();
return byteArrayOutputStream.toByteArray();
}