Android - Save image from URL onto SD card

后端 未结 7 1341
太阳男子
太阳男子 2020-11-28 07:37

I want to save an image from a URL to the SD card (for future use) and then load that image from the SD card to use it as a drawable overlay for Google maps.

Here is

7条回答
  •  生来不讨喜
    2020-11-28 08:11

    Try this... An easy way to the task done.

    Picasso.with(getActivity())
                    .load(url)
                    .into(new Target() {
                              @Override
                              public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                  try {
                                      String root = Environment.getExternalStorageDirectory().toString();
                                      File myDir = new File(root + "/yourDirectory");
    
                                      if (!myDir.exists()) {
                                          myDir.mkdirs();
                                      }
    
                                      String name = new Date().toString() + ".jpg";
                                      myDir = new File(myDir, name);
                                      FileOutputStream out = new FileOutputStream(myDir);
                                      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    
                                      out.flush();
                                      out.close();
                                  } catch(Exception e){
                                      // some action
                                  }
                              }
    
                              @Override
                              public void onBitmapFailed(Drawable errorDrawable) {
                              }
    
                              @Override
                              public void onPrepareLoad(Drawable placeHolderDrawable) {
                              }
                          }
                    );
    

提交回复
热议问题