在我的应用中,用户可以选择图库中的图片作为头像,但我想将其保存到我的应用存储中,以便他们删除该文件。
我的代码是:
//onActivityResult()
else if (requestCode == SELECT_PICTURE)
{
mFile = new File(getRealPathFromURI(data.getData()));
Date d = new Date();
long ms = d.getTime();
mName = String.valueOf(ms) + ".jpg";
copyfile(mFile,mName);
File file = new File(Environment.getExternalStorageDirectory(), mName);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imgPhoto.setImageBitmap(myBitmap);
}
public String getRealPathFromURI(Uri contentUri)
{
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri,proj,null,null,null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void copyfile(File file,String newFileName){
try{
InputStream in = new FileInputStream(file);
OutputStream out = openFileOutput(newFileName, MODE_PRIVATE);
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d(null,"success");
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
如果我在位图中解码mFile,则显示图像,因此mFile具有图像。 ¿有什么想法吗?
答案 0 :(得分:2)
嗯,首先......你还没告诉我们你现在的行为。你的应用崩溃了吗?图片无法显示吗?其他一些意想不到的行为?
除此之外:
不要使用managedQuery()
...它在主UI线程上运行,因此很容易在应用程序中引入延迟。理想情况下,您希望使用CursorLoader
但是将AsyncTask
所有工作包装起来可能更容易(通过"所有工作和#34;我的意思是全部与保存/检索/解码图像文件相关的工作......我建议这样做,因为它可能需要相当长的时间才能完成所有这些工作,如果UI线程也被阻止,你的应用可能看起来很慢长)。
如果您选择将工作包装在AsyncTask
(我建议您这样做),请将所有工作放在doInBackground()
中,并在完成后相应地更新您的用户界面onPostExecute()
。