我正在尝试从MainActivity
的默认相机意图中拍摄照片,然后将该图像放在ImageView
的同一活动中。
我正在保存图像,以便拍摄的图像会覆盖以前拍摄的图像(在这种情况下,我调用图像test.jpg
并将其存储在SD卡中)
我现在对代码的问题是ImageView
显示应用程序上次运行时拍摄的照片。
这是我的代码。
public class MainActivity extends Activity
{
ImageView imv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imv = (ImageView)findViewById(R.id.imv);
Uri uri = null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.jpg";
try
{
uri = takePhoto(path);
}
catch(Exception e)
{
e.printStackTrace();
}
imv.setImageURI(uri);
}
private Uri takePhoto(String path) throws IOException
{
File photo = new File(path);
photo.createNewFile();
Uri fileUri = Uri.fromFile(photo);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, 0);
fileUri = Uri.fromFile(new File(path));
return fileUri;
}
}
答案 0 :(得分:2)
尝试在onActivityResult
中设置图片,如下所示:
protected void onActivityResult(int requestCode, int resultCode, Intent ata)
{
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
imv = (ImageView)findViewById(R.id.imv);
Bitmap photo = (Bitmap) data.getExtras().get("data");
imv.setImageBitmap(photo);
}}}
答案 1 :(得分:0)
private static final int PICK_CONTACT_REQUEST = 0 ;
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
imv.setImageURI(uri);
}
}
}
将图像设置为onactivity结果,它将显示从相机拍摄的新图像。
答案 2 :(得分:0)
试试这个,
private Uri takePhoto(String path) throws IOException
{
File photo = new File(path);
photo.createNewFile();
if(photo.exists())
photo.delete();
photo = new File(path);
Uri fileUri = Uri.fromFile(photo);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, 0);
fileUri = Uri.fromFile(new File(path));
return fileUri;
}