【问题标题】:How to save the image to SD card on button Click android [closed]如何在按钮上将图像保存到 SD 卡单击 android [关闭]
【发布时间】:2012-03-12 20:47:27
【问题描述】:

我在 1 个 XML 中使用 Imageview 和 Button,我正在从 webServer 检索图像作为 URL 并将其显示在 ImageView 上。现在,如果单击按钮(保存),我需要将该特定图像保存到 SD 卡中。如何做到这一点?

注意:应保存当前图像。

【问题讨论】:

标签: android android-layout android-widget


【解决方案1】:

可能的解决方案是

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

    }

【讨论】:

  • 它适用于我的项目.. 谢谢。
【解决方案2】:

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

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

然后您必须从 SD 卡中获取目录(File 对象),例如:

    File sdCardDirectory = Environment.getExternalStorageDirectory();

接下来,创建用于图像存储的特定文件:

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

之后,您只需要编写Bitmap,这要归功于它的方法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"/>

【讨论】:

  • R u 当然,此示例将当前图像保存在 buttonclick 上。我试过但它没有被保存
  • 修正。非常非常清晰的例子..效果很好,谢谢老兄
  • @Romain: 如何以不同的名称保存图像。如果我点击保存其他图像,以前的图像会被覆盖..我们是否需要计算存储在那里的图像数量
  • 是的。例如,您可以在类中使用静态字段来增加已保存图像的数量。之后,您可以使用它来生成文件名。否则,您可以在文件名中使用时间戳。以System.currentTimeMillis() 为例。
  • @RomainR。你能告诉我在使用相机时如何做到这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多