1

我想将图像视图保存到特定文件夹中的图像,我尝试了这段代码,但它不起作用

public void saveImage(View v){  
        View content = findViewById(R.id.iv_photo);
        content.setDrawingCacheEnabled(true);
            Bitmap bitmap = content.getDrawingCache();
            //File file = new File("/DCIM/Camera/image.jpg");
            File root = Environment.getExternalStorageDirectory();
            File file = new File(root.getAbsolutePath() + "/DCIM/image.jpg");
            try {
                file.createNewFile();
                FileOutputStream ostream = new FileOutputStream(file);
                bitmap.compress(CompressFormat.JPEG, 100, ostream);
                ostream.close();
            }catch (Exception e){
                e.printStackTrace();
            }

    }

以及调用函数的这段代码

saveImage(getWindow().getDecorView().findViewById(android.R.id.content));
4

1 回答 1

1

要从应用程序的资源中保存图像文件,您可以这样进行:

File dest = Environment.getExternalStorageDirectory();
InputStream in = context.getResources().getDrawable(R.drawable.my_image);
// Used the File-constructor
OutputStream out = new FileOutputStream(new File(dest, "myNewImage.png"));

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
try {
    // A little more explicit
    while ( (len = in.read(buf, 0, buf.length)) != -1){
         out.write(buf, 0, len);
    }
} finally {
    // Ensure the Streams are closed:
    in.close();
    out.close();
}

这应该可以解决问题。

于 2013-06-18T10:42:39.000 回答