2012-02-22 66 views
8

我在1 XML中使用了一個Imageview和一個按鈕,並且我將這些圖像作爲來自webServer的URL進行檢索並在ImageView上顯示它。現在,如果點擊按鈕(保存),我需要將該特定圖像保存到SD卡。這個怎麼做?如何將圖像保存到按鈕上的SD卡點擊android

注意:應保存當前圖像。

+1

有很多答案是你的問題,使用搜索第一! http://stackoverflow.com/questions/4875114/android-save-image-from-url-onto-sd-card – 2012-02-22 14:03:54

回答

49

首先,你需要得到你的位圖。你已經可以把它作爲一個對象位圖,或者你可以嘗試從ImageView的得到它,例如:

BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable(); 
    Bitmap bitmap = drawable.getBitmap(); 

然後,你必須讓從SD卡目錄(File對象),如:

File sdCardDirectory = Environment.getExternalStorageDirectory(); 

接下來,建立特定的文件存儲圖像:

File image = new File(sdCardDirectory, "test.png"); 

之後,你只需要編寫位圖得益於其方法compress如:

boolean success = false; 

    // Encode the file as a PNG image. 
    FileOutputStream outStream; 
    try { 

     outStream = new FileOutputStream(image); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
     /* 100 to keep full quality of the image */ 

     outStream.flush(); 
     outStream.close(); 
     success = true; 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

最後,如果需要處理布爾結果。如:

if (success) { 
     Toast.makeText(getApplicationContext(), "Image saved with success", 
       Toast.LENGTH_LONG).show(); 
    } else { 
     Toast.makeText(getApplicationContext(), 
       "Error during image saving", Toast.LENGTH_LONG).show(); 
    } 

不要忘記添加以下權限在您的清單:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
+0

ü當然,這個例子將當前圖像保存在buttonclick.I嘗試,但它沒有得到保存 – 2012-02-23 05:09:05

+0

Rectified.Very非常清楚的例子..Works偉大,謝謝兄弟 – 2012-02-23 05:43:22

+0

@ Romain:如何保存圖像在不同的名稱。如果我點擊以保存其他圖像先前的圖像被覆蓋。我們是否需要計算存儲在那裏的圖像數量 – 2012-02-23 06:11:52

5

問題解決方法是

Android - Saving a downloaded image from URL onto SD card

Bitmap bitMapImg; 
void saveImage() { 
     File filename; 
     try { 
      String path = Environment.getExternalStorageDirectory().toString(); 

      new File(path + "/folder/subfolder").mkdirs(); 
      filename = new File(path + "/folder/subfolder/image.jpg"); 

      FileOutputStream out = new FileOutputStream(filename); 

      bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out); 
      out.flush(); 
      out.close(); 

      MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName()); 

      Toast.makeText(getApplicationContext(), "File is Saved in " + filename, 1000).show(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 
+0

bmImg顯示null man – 2012-02-23 05:23:14

+1

它在我的項目中工作..謝謝。 – Drx 2013-07-24 08:18:39