在我的应用程序中,用户可以从他们的图库中选择一张图片作为头像,但我想将其保存到我的应用程序存储中,以便他们可以删除文件。
我的代码是:
//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 具有图像。有任何想法吗?