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

Kal*_*n.G 8 android android-widget android-layout

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

注意:当前图像应保存.

Rom*_* R. 50

首先,您需要获取您的位图.您已经可以将它作为对象Bitmap,或者您可以尝试从ImageView获取它,例如:

    BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
    Bitmap bitmap = drawable.getBitmap();
Run Code Online (Sandbox Code Playgroud)

然后你必须从SD卡到达目录(一个File对象),例如:

    File sdCardDirectory = Environment.getExternalStorageDirectory();
Run Code Online (Sandbox Code Playgroud)

接下来,为图像存储创建特定文件:

    File image = new File(sdCardDirectory, "test.png");
Run Code Online (Sandbox Code Playgroud)

之后,由于其方法压缩,您只需编写位图,例如:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

最后,如果需要,只需处理布尔结果.如:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)


pra*_*upd 5

可能的解决方案是

Android - 将下载的图像从URL保存到SD卡

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

    }
Run Code Online (Sandbox Code Playgroud)