[英]Trying to display image taken from camera intent
I'm Currently trying to take a photo from the default camera intent from the MainActivity
and then put that image in an ImageView
in the same activity. 我目前正在尝试从MainActivity
的默认相机意图拍摄照片,然后将该图像放入同一活动的ImageView
中。
I'm saving the images such that the image taken overwrites the previously taken image (In this case, I call the image test.jpg
and I store it in sdcard) 我正在保存图像,以使拍摄的图像覆盖先前拍摄的图像(在这种情况下,我将图像称为test.jpg
并将其存储在sdcard中)
The problem I have with my code right now is the ImageView
displays the photo taken the previous time the application ran. 我的代码现在遇到的问题是ImageView
显示了应用程序上次运行时拍摄的照片。
Here is my code. 这是我的代码。
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;
}
}
Try to set image in onActivityResult
as below: 尝试在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);
}}}
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);
}
}
}
Set the image in onactivity result it will show new Image taken from the camera . 将图像设置为不活动状态,它将显示从相机拍摄的新图像。
Try this, 尝试这个,
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.