在android中将图像写入外部存储器

时间:2013-12-09 23:26:00

标签: android image storage external

我使用以下代码将图像写入android中的外部存储:

File root = android.os.Environment.getExternalStorageDirectory(); 
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs(); 
fileName = "image_2.jpeg";
File file = new File(dir, fileName);

try {
    FileOutputStream outStream = new FileOutputStream(file);
    Bitmap bitmap = BitmapFactory.decodeFile("android.resource://com.mypackage.com/drawable/image_1");
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outStream);
    outStream.flush();
    outStream.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}   

此代码用于从drawable文件夹中读取image_1.jpg,然后使用image_2.jpeg名称将其写入外部存储中的下载文件夹。 (在外部存储中创建下载文件夹,在该文件夹中创建image_2.jpeg名称的文件)。 此代码将生成((强制关闭))。创建了下载文件夹,并且还创建了image_2.jpeg,但图像image_2.jpeg已损坏。

2 个答案:

答案 0 :(得分:1)

可绘制文件夹中的这些图像可以通过BitmapFactory访问,您可以将位图保存为PNG或JPG。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png";
File dest = new File(sd, fileName);
try {
    FileOutputStream out;
    out = new FileOutputStream(dest);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    out.flush();
    out.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

不要忘记添加android.permission.WRITE_EXTERNAL_STORAGE权限。

对于其他类型的图像,我认为将它们放入资源文件夹是一种更好的方法。

There is a sample here.

答案 1 :(得分:0)

我对此代码做了同样的事情。试试这段代码:

String[] sampleImagesName = { "image2" };
int[] sampleImages = { R.drawable.image1};
File file;
if (Environment.getExternalStorageState().equals(
    Environment.MEDIA_MOUNTED)) {
    file = new File(Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/download");
    if (!file.exists()) {
        file.mkdirs();
        SaveSampleToSD();
    }
}
private void SaveSampleToSD() {
        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/download";

        for (int i = 0; i < sampleImages.length; i++) {
            try {
                File f = new File(path + "/", sampleImagesName[i] + ".jpg");
                Bitmap bm = BitmapFactory.decodeResource(getResources(),
                        sampleImages[i]);
                FileOutputStream out = new FileOutputStream(f);
                bm.compress(Bitmap.CompressFormat.JPEG, 100, out);

                out.flush();
                out.close();

                Log.e("ImageSaved---------", "saved");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }