0

我創建了一個包含圖像和下載按鈕的佈局。我不知道如何將imageView下載到我的SD卡。我在stackoverflow上搜索了很多,但沒有完美的答案可用。如何將imageView保存到我的SD卡?

代碼: imageView.xml

<RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools"  
     android:layout_width="match_parent" 
     android:layout_height="match_parent"  
     android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     android:paddingBottom="@dimen/activity_vertical_margin"  
     tools:context=".MainActivity"> 

<ImageView 
    android:id="@+id/image" 
    android:layout_height="match_parent" 
    android:src="@drawable/image" 
    android:layout_width="fill_parent" 
    android:fitsSystemWindows="true" 
    android:scaleType="fitStart"/> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Change" 
    android:id="@+id/button" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" /> 

</RelativeLayout> 


public class MainActivity extends AppCompatActivity { 

Button button; 
ImageView imageView; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    addListenerOnButton(); 
}} 
+0

存儲在服務器上的實際圖像? –

+1

http://stackoverflow.com/questions/14135764/store-image-to-sd-card –

+0

圖像在哪裏!? –

回答

0

這裏:

,添加以下權限在你的清單:

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

後來:

BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable(); 
    Bitmap bitmap = drawable.getBitmap(); 
File sdCardDirectory = Environment.getExternalStorageDirectory(); 
    File image = new File(sdCardDirectory, "test.png"); 

    boolean success = false; 

    // Encode 
    FileOutputStream outStream; 
    try { 

     outStream = new FileOutputStream(image); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
     /* 100 keep full quality 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, OK", 
       Toast.LENGTH_LONG).show(); 
    } else { 
     Toast.makeText(getApplicationContext(), 
       "Error during image saving", Toast.LENGTH_LONG).show(); 
    }