[英]Eclipse: save image from drawable resource
I have to save an image in to a gallery from a drawable resource with a button and I have use this code: 我必须使用按钮将图像从可绘制资源保存到库中,我使用此代码:
@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();
}
now the problem is that i save a file of 0kb... oo 现在的问题是我保存了一个0kb ... oo的文件
Thanks in advance . 提前致谢 。
Try this: 尝试这个:
OutputStream os = new FileOutputStream(new File("path/to/file"));
Beware, though. 但要注意。 The way you copy data between the streams may easily lead to heap overflow if the resource is large.
如果资源很大,在流之间复制数据的方式很容易导致堆溢出。 You should consider a smaller buffer reused as many times as needed to copy the whole data:
您应该根据需要多次重复使用较小的缓冲区来复制整个数据:
byte[] data = new byte[1024];
int len = 0;
while ((len = is.read(data)) > -1) {
os.write(data, 0, len);
}
Another consideration would be to move the whole copy operation to a separate thread (eg using AsyncTask) as not to block the UI thread. 另一个考虑因素是将整个复制操作移动到一个单独的线程(例如使用AsyncTask),而不是阻止UI线程。 See the example here: http://developer.android.com/reference/android/os/AsyncTask.html
请参阅此处的示例: http : //developer.android.com/reference/android/os/AsyncTask.html
I don't know, if there is a better solution, but this code works for me: 我不知道,如果有更好的解决方案,但这段代码对我有用:
//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();
Please make sure you have added this line in your manifest.xml: 请确保您在manifest.xml中添加了以下行:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.