【问题标题】:Saving multiple images to external storage android将多个图像保存到外部存储android
【发布时间】:2013-05-17 23:01:04
【问题描述】:

我的 res/drawable 文件夹中有 50 多张图像。我想将这些图像保存到外部存储中,然后在图像视图/图像切换器中一张一张地显示这些图像。我使用下面的代码将单个图像保存到外部存储。但我无法弄清楚如何将所有这些图像完全保存到外部存储中(一次)。

public void SaveImage(){
    if (!CheckExternalStorage()) {
        return;
    }

    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a01);
    try {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        OutputStream fOut = null;
        File file = new File(path, "image1.png");
        file.createNewFile();
        fOut = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        Log.i(LOGTAG, "Image Written to Exterbal Storage");

    } catch (Exception e) {
        Log.e("saveToExternalStorage()", e.getMessage());
    }


}

【问题讨论】:

  • for(...) 循环有什么问题?
  • @Stochasticly 是的,这是一个好主意,但是如何在这一行上迭代循环 Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a01);
  • 看起来答案找到了方法:-)。
  • :-/ 我会试试看 ;-)

标签: android


【解决方案1】:

使用来自 https://stackoverflow.com/a/3221787/794088 的答案并进行一些修改以使用参数调用您的方法 SaveImage

...
R.drawable drawableResources = new R.drawable();
Class<R.drawable> c = R.drawable.class;
Field[] fields = c.getDeclaredFields();

for (int i = 0, max = fields.length; i < max; i++) {
    final int resourceId;
    try {
        resourceId = fields[i].getInt(drawableResources);
        // call save with param of resourceId
        SaveImage(resourceId);
    } catch (Exception e) {
        continue;
    }
}

...

public void SaveImage(int resId){
    if (!CheckExternalStorage()) {
        return;
    }

    Bitmap bmp = BitmapFactory.decodeResource(getResources(), resID);
    try {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        OutputStream fOut = null;
        File file = new File(path, "image1.png");
        file.createNewFile();
        fOut = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        Log.i(LOGTAG, "Image Written to Exterbal Storage");

    } catch (Exception e) {
        Log.e("saveToExternalStorage()", e.getMessage());
    }


}

【讨论】:

  • 请不要忘记在顶部为链接的答案投票(如果你觉得它有用的话)。
猜你喜欢
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
相关资源
最近更新 更多