如何将图像保存到SD卡上按钮单击android

时间:2012-02-22 13:58:25

标签: android android-layout android-widget

我正在使用1个XML中的Imageview和Button,我正在从webServer中将图像作为URL重新显示并在ImageView上显示它。现在,如果单击按钮(保存),我需要将该特定图像保存到SD卡中。怎么做?

注意:应保存当前图像。

2 个答案:

答案 0 :(得分:49)

首先,您需要获取您的位图。您已经可以将它作为对象Bitmap,或者您可以尝试从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();
    }

不要忘记在Manifest中添加以下权限:

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

答案 1 :(得分: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();
        }

    }