Android保存多張圖片到本地

目錄介紹

  • 01.實際開發保存圖片遇到的問題
  • 02.直接用http請求圖片並保存本地
  • 03.用glide下載圖片保存本地
  • 04.如何實現連續保存多張圖片
  • 05.關於其餘介紹

給本身相個親

好消息

  • 博客筆記大彙總【16年3月到至今】,包括Java基礎及深刻知識點,Android技術博客,Python學習筆記等等,還包括平時開發中遇到的bug彙總,固然也在工做之餘收集了大量的面試題,長期更新維護而且修正,持續完善……開源的文件是markdown格式的!同時也開源了生活博客,從12年起,積累共計N篇[近100萬字,陸續搬到網上],轉載請註明出處,謝謝!
  • 連接地址:github.com/yangchong21…
  • 若是以爲好,能夠star一下,謝謝!固然也歡迎提出建議,萬事起於忽微,量變引發質變!

01.實際開發保存圖片遇到的問題

  • 業務需求
    • 在素材list頁面的九宮格素材中,展現網絡請求加載的圖片。若是用戶點擊保存按鈕,則保存若干張圖片到本地。具體作法是,使用glide加載圖片,而後設置listener監聽,在圖片請求成功onResourceReady後,將圖片資源resource保存到集合中。這個時候,若是點擊保存控件,則循環遍歷圖片資源集合保存到本地文件夾。
  • 具體作法代碼展現
    • 這個時候直接將請求網絡的圖片轉化成bitmap,而後存儲到集合中。而後當點擊保存按鈕的時候,將會保存該組集合中的多張圖片到本地文件夾中。
    //bitmap圖片集合
    private ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();
    
    
    RequestOptions requestOptions = new RequestOptions()
            .transform(new GlideRoundTransform(mContext, radius, cornerType));
    GlideApp.with(mIvImg.getContext())
            .asBitmap()
            .load(url)
            .listener(new RequestListener<Bitmap>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model,
                                            Target<Bitmap> target, boolean isFirstResource) {
                    return true;
                }
    
                @Override
                public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target,
                                               DataSource dataSource, boolean isFirstResource) {
                    bitmapArrayList.add(resource);
                    return false;
                }
            })
            .apply(requestOptions)
            .placeholder(ImageUtils.getDefaultImage())
            .into(mIvImg);
            
            
            
    //循環遍歷圖片資源集合,而後開始保存圖片到本地文件夾
    mBitmap = bitmapArrayList.get(i);
    savePath = FileSaveUtils.getLocalImgSavePath();
    FileOutputStream fos = null;
    try {
        File filePic = new File(savePath);
        if (!filePic.exists()) {
            filePic.getParentFile().mkdirs();
            filePic.createNewFile();
        }
        fos = new FileOutputStream(filePic);
        // 100 圖片品質爲滿
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //刷新相冊
        if (isScanner) {
            scanner(context, savePath);
        }
    }
    複製代碼
  • 遇到的問題
    • 保存圖片到本地後,發現圖片並非原始的圖片,而是展示在view控件上被裁切的圖片,也就是ImageView的尺寸大小圖片。
  • 爲何會遇到這種問題
    • 若是你傳遞一個ImageView做爲.into()的參數,Glide會使用ImageView的大小來限制圖片的大小。例如若是要加載的圖片是1000x1000像素,可是ImageView的尺寸只有250x250像素,Glide會下降圖片到小尺寸,以節省處理時間和內存。
    • 在設置into控件後,也就是說,在onResourceReady方法中返回的圖片資源resource,實質上不是你加載的原圖片,而是ImageView設定尺寸大小的圖片。因此保存以後,你會發現圖片變小了。
  • 那麼如何解決問題呢?
    • 第一種作法:九宮格圖片控件展現的時候會加載網絡資源,而後加載圖片成功後,則將資源保存到集合中,點擊保存則循環存儲集合中的資源。這種作法只會請求一個網絡。因爲開始
    • 第二種作法:九宮格圖片控件展現的時候會加載網絡資源,點擊保存九宮格圖片的時候,則依次循環請求網絡圖片資源而後保存圖片到本地,這種作法會請求兩次網絡。

02.直接用http請求圖片並保存本地

  • http請求圖片
    /**
     * 請求網絡圖片
     * @param url                       url
     * @return                          將url圖片轉化成bitmap對象
     */
    private static long time = 0;
    public static InputStream HttpImage(String url) {
        long l1 = System.currentTimeMillis();
        URL myFileUrl = null;
        Bitmap bitmap = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(5000);
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                    conn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            long l2 = System.currentTimeMillis();
            time = (l2-l1) + time;
            LogUtils.e("毫秒值"+time);
            //保存
        }
        return is;
    }
    複製代碼
  • 保存到本地
    InputStream inputStream = HttpImage(
            "https://img1.haowmc.com/hwmc/material/2019061079934131.jpg");
    String localImgSavePath = FileSaveUtils.getLocalImgSavePath();
    File imageFile = new File(localImgSavePath);
    if (!imageFile.exists()) {
        imageFile.getParentFile().mkdirs();
        try {
            imageFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    FileOutputStream fos = null;
    BufferedInputStream bis = null;
    try {
        fos = new FileOutputStream(imageFile);
        bis = new BufferedInputStream(inputStream);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    複製代碼

03.用glide下載圖片保存本地

  • glide下載圖片
    File file = Glide.with(ReflexActivity.this)
            .load(url.get(0))
            .downloadOnly(500, 500)
            .get();
    複製代碼
  • 保存到本地
    String localImgSavePath = FileSaveUtils.getLocalImgSavePath();
    File imageFile = new File(localImgSavePath);
    if (!imageFile.exists()) {
        imageFile.getParentFile().mkdirs();
        imageFile.createNewFile();
    }
    copy(file,imageFile);
    
    /**
     * 複製文件
     *
     * @param source 輸入文件
     * @param target 輸出文件
     */
    public static void copy(File source, File target) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    複製代碼

04.如何實現連續保存多張圖片

  • 思路:循環子線程
    • 可行(不推薦), 若是我要下載9個圖片,將子線程加入for循環內,並最終呈現。
    • 有嚴重缺陷,線程延時,圖片順序不能作保證。若是是線程套線程的話,第一個子線程結束了,嵌套在該子線程f的or循環內的子線程還沒結束,從而主線程獲取不到子線程裏獲取的圖片。
    • 還有就是如何判斷全部線程執行完畢,好比全部圖片下載完成後,吐司下載完成。
  • 不建議的方案
    • 建立一個線程池來管理線程,關於線程池封裝庫,能夠看線程池簡單封裝
    • 這種方案不知道全部線程中請求圖片是否所有完成,且不能保證順序。
    ArrayList<String> images = new ArrayList<>();
    for (String image : images){
        //使用該線程池,及時run方法中執行異常也不會崩潰
        PoolThread executor = BaseApplication.getApplication().getExecutor();
        executor.setName("getImage");
        executor.execute(new Runnable() {
            @Override
            public void run() {
                //請求網絡圖片並保存到本地操做
            }
        });
    }
    複製代碼
  • 推薦解決方案
    ArrayList<String> images = new ArrayList<>();
    ApiService apiService = RetrofitService.getInstance().getApiService();
    //注意:此處是保存多張圖片,能夠採用異步線程
    ArrayList<Observable<Boolean>> observables = new ArrayList<>();
    final AtomicInteger count = new AtomicInteger();
    for (String image : images){
        observables.add(apiService.downloadImage(image)
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, Boolean>() {
                    @Override
                    public Boolean apply(ResponseBody responseBody) throws Exception {
                        saveIo(responseBody.byteStream());
                        return true;
                    }
                }));
    }
    // observable的merge 將全部的observable合成一個Observable,全部的observable同時發射數據
    Disposable subscribe = Observable.merge(observables).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean b) throws Exception {
                    if (b) {
                        count.addAndGet(1);
                        Log.e("yc", "download is succcess");
    
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.e("yc", "download error");
                }
            }, new Action() {
                @Override
                public void run() throws Exception {
                    Log.e("yc", "download complete");
                    // 下載成功的數量 和 圖片集合的數量一致,說明所有下載成功了
                    if (images.size() == count.get()) {
                        ToastUtils.showRoundRectToast("保存成功");
                    } else {
                        if (count.get() == 0) {
                            ToastUtils.showRoundRectToast("保存失敗");
                        } else {
                            ToastUtils.showRoundRectToast("因網絡問題 保存成功" + count + ",保存失敗" + (images.size() - count.get()));
                        }
                    }
                }
            }, new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    Log.e("yc","disposable");
                }
            });
            
            
            
    private void saveIo(InputStream inputStream){
        String localImgSavePath = FileSaveUtils.getLocalImgSavePath();
        File imageFile = new File(localImgSavePath);
        if (!imageFile.exists()) {
            imageFile.getParentFile().mkdirs();
            try {
                imageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        try {
            fos = new FileOutputStream(imageFile);
            bis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //刷新相冊代碼省略……
        }
    }
    複製代碼

其餘介紹

01.關於博客彙總連接

02.關於個人博客

項目案例:github.com/yangchong21…

相關文章
相關標籤/搜索