1. 程式人生 > >Glide實現查看圖片和保存圖片到手機

Glide實現查看圖片和保存圖片到手機

查看圖片 otf asynctask tlist bitmap ready env pic blank

兩種方式, 推薦方式一

方式一 downloadOnly

創建一個 ImageActivity

public class ImageActivity extends AppCompatActivity {

    private static final String TAG = "ImageActivity";

    private ImageView iv;

    Bitmap bitmap;

    private String mUrl;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); iv = (ImageView) findViewById(R.id.iv); // 圖片的url 從另一個Activity傳過來 String url = getIntent().getStringExtra(EXTRA_URL); mUrl = url; loadImage(url); // 長按 ImageView 把圖片保存到手機
iv.setOnLongClickListener(new View.OnLongClickListener(){ @Override public boolean onLongClick(View v) { download(mUrl) return true; } }); } public void loadImage(String url) { Glide.with(
this).load(url).placeholder(R.drawable.image_loading) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { Log.d(TAG, "onResourceReady: mode: " + model); // 如果return true; 則 into(iv) 不起作用, 要手動設置圖片 // iv.setImageDrawable(resource); return false; } }) .into(iv); } public void download(final String url) { new AsyncTask<Void, Integer, File>() { @Override protected File doInBackground(Void... params) { File file = null; try { FutureTarget<File> future = Glide .with(ImageActivity.this) .load(url) .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL); file = future.get(); // 首先保存圖片 File pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile(); File appDir = new File(pictureFolder ,"Beauty"); if (!appDir.exists()) { appDir.mkdirs(); } String fileName = System.currentTimeMillis() + ".jpg"; File destFile = new File(appDir, fileName); FileUtil.copy(file, destFile); // 最後通知圖庫更新 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(destFile.getPath())))); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return file; } @Override protected void onPostExecute(File file) { Toast.makeText(ImageActivity.this, "saved in Pictures/GankBeauty", Toast.LENGTH_SHORT).show(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } }.execute(); } }

以上代碼 從另一個activity得到 圖片的 url , 然後使用Glide 圖片加載庫 將圖片顯示到 ImageView上, 長按ImageView可以將圖片保存到手機的 Pictures/Beauty 目錄中

這是基本的代碼模板, 實際情況更復雜,比如Android 6 還有運行時申請存儲權限的問題。

方式二 asBitmap bitmap.compress

還有一種保存圖片的方式也有很多人用,但是經過我對比發現並不好,推薦上面的方式。另一種方式的代碼如下

把上面 loadImage 換成 下面的 loadBitmap

    public void loadBitmap(String url) {
        Glide.with(this).load(url).asBitmap().placeholder(R.drawable.image_loading)
                .listener(new RequestListener<String, Bitmap>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {

                        Log.i(TAG, "onResourceReady: thread is " + Thread.currentThread().getName());
                        isReady = true;
                        bitmap = resource;
                        iv.setImageBitmap(resource);
 

                        return false;
                    }
                })
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

    }

把上面的 download 換成下面的 saveImage

public void saveImage() {

        // 首先保存圖片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();

        File appDir = new File(file ,"Beauty");
        boolean createed = false;
        if (!appDir.exists()) {
            createed =  appDir.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, fileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bitmap.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();
            }
        }


        // 最後通知圖庫更新
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));



    }

這種方式把圖片變成bitmap , 保存的時候又重新壓縮bitmap 保存到手機。

總結

從電腦下載圖片,然後與保存到手機的圖片對比,發現bitmap的方式得到的圖片體積變大。

而第一種方式下載的圖片與從電腦上下載的圖片體積一致,md5一致。

所以推薦downloadOnly方式

作者:Panda Fang

出處:http://www.cnblogs.com/lonkiss/p/7119062.html

原創文章,轉載請註明作者和出處,未經允許不可用於商業營利活動

Glide實現查看圖片和保存圖片到手機