我必须使用按钮将图像从可绘制资源保存到图库中,并且我已使用此代码:
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher3);
//generate file
String SDdirectory = Environment.getExternalStorageDirectory().getPath();
File externalStorageDir = Environment.getExternalStorageDirectory();
File f = new File(externalStorageDir, "Bitmapname.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG,0 , bos);
byte[] bitmapdata = bos.toByteArray();
try {
OutputStream os = new FileOutputStream (new File ("storage/sdcard0/iob"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
现在的问题是我保存了一个0kb ... o.o
的文件提前致谢。
答案 0 :(得分:1)
试试这个:
OutputStream os = new FileOutputStream(new File("path/to/file"));
但是,请注意。如果资源很大,在流之间复制数据的方式很容易导致堆溢出。您应该根据需要多次重复使用较小的缓冲区来复制整个数据:
byte[] data = new byte[1024];
int len = 0;
while ((len = is.read(data)) > -1) {
os.write(data, 0, len);
}
另一个考虑因素是将整个复制操作移动到一个单独的线程(例如使用AsyncTask),而不是阻止UI线程。请参阅此处的示例:http://developer.android.com/reference/android/os/AsyncTask.html
答案 1 :(得分:1)
我不知道,如果有更好的解决方案,但这段代码对我有用:
//at first I've imported the bitmap normally.
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.wall);
//generate file
File dir = new File ("/sdcard/foldername/");
File f = new File(dir, String.format("mybitmapname.png"));
//then write it to galery by adding this lines
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 , bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
bos.close();
请确保您已在manifest.xml中添加此行:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 2 :(得分:0)