这是用于拍照并保存到外部存储的工作代码以及另一种保存到设备上“文件”目录的方法。在我的情况下,我只需要一张图像(something.png),在用户拍摄新照片后总是会刷新。
用户单击相机按钮时的操作:
ImageView productImageView = (ImageView) findViewById(R.id.imageView1);
static int RESULT_TAKE_PICTURE = 1;
String selectedImagePath;
Bitmap bitmap;
String imageName = "something.png";
public void cameraImageButton_onClick(View view) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String path = Environment.getExternalStorageDirectory()
+ File.separator + Environment.DIRECTORY_PICTURES;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
dir = new File(path, imageName);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(dir));
startActivityForResult(cameraIntent, RESULT_TAKE_PICTURE);
}
对活动结果执行的操作:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_TAKE_PICTURE && resultCode == RESULT_OK) {
selectedImagePath = Environment.getExternalStorageDirectory()
+ File.separator + Environment.DIRECTORY_PICTURES
+ File.separator + imageName;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
options.inSampleSize = Calculator.calculateInSampleSize(options,
254, 254);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(selectedImagePath, options);
productImageView.setImageBitmap(bitmap);
saveImage(bitmap, imageName);
}
}
如果有人需要,将图像保存到文件目录中的设备的奖励方法:
private void saveImage(Bitmap bitmap, String name) {
String path = getApplicationContext().getFilesDir().toString()
+ File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
path = path + name;
dir = new File(path);
try {
dir.createNewFile();
FileOutputStream fos = new FileOutputStream(dir);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}