Android:經過Glide保存圖片到本地,並同步到相冊

 1 save.setOnClickListener(new View.OnClickListener() {  2  @Override  3                 public void onClick(View v) {  4                     Glide.with(itemActivity.this)  5  .asBitmap()  6  .load(url)  7                             .into(new SimpleTarget<Bitmap>() {  8  @Override  9                                 public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { 10  saveImage(resource); 11  } 12  }); 13 
14  } 15  }); 16 
17 private void saveImage(Bitmap image) { 18         String saveImagePath = null; 19         Random random = new Random(); 20         String imageFileName = "JPEG_" + "down" + random.nextInt(10) + ".jpg"; 21         File storageDir = new File(Environment.getExternalStoragePublicDirectory 22                 (Environment.DIRECTORY_PICTURES) + "test"); 23 
24         boolean success = true; 25         if(!storageDir.exists()){ 26             success = storageDir.mkdirs(); 27  } 28         if(success){ 29             File imageFile = new File(storageDir, imageFileName); 30             saveImagePath = imageFile.getAbsolutePath(); 31             try { 32                 OutputStream fout = new FileOutputStream(imageFile); 33                 image.compress(Bitmap.CompressFormat.JPEG, 100, fout); 34  fout.close(); 35             } catch (Exception e) { 36  e.printStackTrace(); 37  } 38 
39             // Add the image to the system gallery
40  galleryAddPic(saveImagePath); 41             Toast.makeText(mContext, "IMAGE SAVED", Toast.LENGTH_LONG).show(); 42  } 43 // return saveImagePath;
44  } 45 
46     private void galleryAddPic(String imagePath) { 47         Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 48         File f = new File(imagePath); 49         Uri contentUri = Uri.fromFile(f); 50  mediaScanIntent.setData(contentUri); 51  sendBroadcast(mediaScanIntent); 52     }
相關文章
相關標籤/搜索