如何将imageView保存到我的SD卡?

时间:2015-10-29 13:21:37

标签: java android android-layout android-intent android-activity

我创建了一个包含图像和下载按钮的布局。我不知道如何将imageView下载到我的SD卡。我在stackoverflow上搜索了很多,但没有完美的答案。

代码: 的 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();
}}

1 个答案:

答案 0 :(得分:0)

下面:

在Manifest中添加以下权限:

<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();
    }