我不想将我的Android应用程序图像存储在内部或外部设备存储中,这样它将对库可见。
现在,我正在外部设备存储中保存我的应用程序图像。但是我想把图像保存到应用程序的私有目录中。我怎样才能做到这一点?
活动
代码:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
File file = new File(path);
Bitmap bmp = CommonMethod.compressImage(file, getContext());
Log.e(TAG, "onActivityResult --: " + String.format("Size : %s", getReadableFileSize(file.length())));
mCustomerImage = CommonMethod.bitmapToByteArray(bmp);
imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
Log.e(TAG, "image: " + imageTemplateStr);
//CommonMethod.SaveImage(bmp);
imageCustomer.setImageBitmap(bmp);
CommonMethod.SaveImage(bmp);
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
File file = new File(path);
Bitmap bmp = CommonMethod.compressImage(file, getContext());
Log.e(TAG, "onActivityResult --: " + String.format("Size : %s", getReadableFileSize(file.length())));
mCustomerImage = CommonMethod.bitmapToByteArray(bmp);
imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
//CommonMethod.SaveImage(bmp);
Log.e(TAG, "image: " + imageTemplateStr);
imageCustomer.setImageBitmap(bmp);
CommonMethod.SaveImage(bmp);
}
}
}
}
SaveImage方法
public static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/.safco_private_pics");
if (!myDir.exists()) {
myDir.mkdirs();
}
File newFile = new File(root,".nomedia");
try {
FileWriter writer = new FileWriter(newFile);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}