1. 程式人生 > >Glide下載圖片並儲存到指定路徑

Glide下載圖片並儲存到指定路徑


importandroid.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import com.bumptech.glide.Glide;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/** 圖片下載 */ public class DownLoadImage implements Runnable { private String url; private Context context; private ImageDownLoadCallBack callBack; private File currentFile; public DownLoadImage(Context context, String url, ImageDownLoadCallBack callBack) { this.url = url; this
.callBack = callBack; this.context = context; } @Override public void run() { File file = null; Bitmap bitmap = null; try { // file = Glide.with(context) // .load(url) // .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
// .get(); bitmap = Glide.with(context) .load(url) .asBitmap().into(200, 200) .get(); if (bitmap != null){ // 在這裡執行圖片儲存方法 saveImageToGallery(context,bitmap); } } catch (Exception e) { e.printStackTrace(); } finally { // if (file != null) { // callBack.onDownLoadSuccess(file); // } else { // callBack.onDownLoadFailed(); // } if (bitmap != null && currentFile.exists()) { callBack.onDownLoadSuccess(bitmap); } else { callBack.onDownLoadFailed(); } } } public void saveImageToGallery(Context context, Bitmap bmp) { // 首先儲存圖片 File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手機必須這樣獲得public絕對路徑 String fileName = "ningjing"; File appDir = new File(file ,fileName); if (!appDir.exists()) { appDir.mkdirs(); } fileName = System.currentTimeMillis() + ".jpg"; currentFile = new File(appDir, fileName); FileOutputStream fos = null; try { fos = new FileOutputStream(currentFile); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } // 其次把檔案插入到系統圖庫 // try { // MediaStore.Images.Media.insertImage(context.getContentResolver(), // currentFile.getAbsolutePath(), fileName, null); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // 最後通知相簿更新 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(currentFile.getPath())))); } }