How To Take A Picture To Show In A `imageview` And Save The Picture?
I need to take a picture with the camera, save the picture, show in ImageView and when I click the Imageview show in fullscreen mode . In the future will need to send the picture t
Solution 1:
You can invoke camera Activity by adding these lines in your code :
Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
privatestaticintRESULT_IMAGE_CLICK=1;
cameraImageUri = getOutputMediaFileUri(1);
// set the image file name
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
startActivityForResult(intent, RESULT_IMAGE_CLICK);
Now create file Uri
because in some android phones you will get null
data in return
so here is the method to get the image URI
:
/** Create a file Uri for saving an image or video */privatestaticUrigetOutputMediaFileUri(int type) {
returnUri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */privatestaticFilegetOutputMediaFile(int type) {
// Check that the SDCard is mountedFile mediaStorageDir = newFile(
Environment.getExternalStorageDirectory(), Environment.DIRECTORY_PICTURES);
// Create the storage directory(MyCameraVideo) if it does not existif (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Item Attachment",
"Failed to create directory MyCameraVideo.");
returnnull;
}
}
java.util.Date date = new java.util.Date();
String timeStamp = getTimeStamp();
File mediaFile;
if (type == 1) {
// For unique video file name appending current timeStamp with file// name
mediaFile = newFile(mediaStorageDir.getPath() + File.separator +abc+ ".jpg");
} else {
returnnull;
}
return mediaFile;
}
For retrieving clicked image :
@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == RESULT_IMAGE_CLICK) {
// Here you have the ImagePath which you can set to you image view
Log.e("Image Name", cameraImageUri.getPath());
BitmapmyBitmap= BitmapFactory.decodeFile(cameraImageUri.getPath());
yourImageView.setImageBitmap(myBitmap);
// For further image Upload i suppose your method for image upload is UploadImageFileimageFile=newFile(cameraImageUri.getPath());
uploadImage(imageFile);
}
}
}
Solution 2:
MainActivity.class
package edu.gvsu.cis.masl.camerademo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
publicclassMyCameraActivityextendsActivity {
privatestaticfinalintCAMERA_REQUEST=1888;
private ImageView imageView;
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
ButtonphotoButton= (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
IntentcameraIntent=newIntent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmapphoto= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/photo" ></Button><ImageViewandroid:id="@+id/imageView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/icon" ></ImageView></LinearLayout>
Make sure your all id would be correct.
Anything you need to know, hassle free to contact me.
Solution 3:
Since there is no proper solution for this, I will put here what I have put together that is working and correct.
ImageButtontakepic= (ImageButton) returnView.findViewById(R.id.takepic);
takepic.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) { Intentintent=newIntent();
addPhoto();
}
});
Android Manifest :
<providerandroid:name="android.support.v4.content.FileProvider"android:authorities="com.example.android.fileprovider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths"></meta-data></provider>
Android Manifest again at the top :
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
External res/xml/file_paths.xml file:
<?xml version="1.0" encoding="utf-8"?><paths><external-files-pathname="my_images" /></paths>
CreateImageFile Function
private File createImageFile()throws IOException {
// Create an image file nameStringtimeStamp=newSimpleDateFormat("yyyyMMdd_HHmmss").format(newDate());
StringimageFileName="JPEG_" + timeStamp + "_";
storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Fileimage= File.createTempFile(
imageFileName, /* prefix */".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
AddPhoto Function
privatevoidaddPhoto() {
// Camera.final List<Intent> cameraIntents = newArrayList<Intent>();
finalIntentcaptureIntent=newIntent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
finalPackageManagerpackageManager= getActivity().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
finalStringpackageName= res.activityInfo.packageName;
finalIntentintent=newIntent(captureIntent);
intent.setComponent(newComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.MEDIA_IGNORE_FILENAME, ".nomedia");
cameraIntents.add(intent);
}
// Filesystem.finalIntentgalleryIntent=newIntent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.finalIntentchooserIntent= Intent.createChooser(galleryIntent, "profileimg");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(newParcelable[]{}));
FilephotoFile=null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully createdif (photoFile != null) {
UriphotoURI= FileProvider.getUriForFile(getContext(),
"com.example.android.fileprovider",
photoFile);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(chooserIntent, 100);}
}
On activity callback
@OverridepublicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
try {
Bundleextras= data.getExtras();
Uriuri= data.getData();
ImageButtontakepic= (ImageButton) returnView.findViewById(R.id.takepic);
if (extras!=null){
BitmapimageBitmap= (Bitmap) extras.get("data");
Log.d(TAG, "onActivityResult: "+mCurrentPhotoPath);
takepic.setImageBitmap(imageBitmap);
}
StringwholeID= DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the arrayStringidx= wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal toStringsel= MediaStore.Images.Media._ID + "=?";
Cursorcursor= getContext().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, newString[]{idx}, null);
StringfilePath="";
intcolumnIndex= cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
Bitmapbitmap= MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
takepic.setImageBitmap(bitmap);
Toast.makeText(getContext(), "Uploading In Progress",
Toast.LENGTH_LONG);
}catch(Exception e){
e.getMessage();
}
}}
Solution 4:
Try this, to save image to file explorer:
publicvoidcaptureImage(View v) {
Intentcamera_intent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
Filef=newFile(Environment.getExternalStorageDirectory(), "image.png");
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
}
publicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode== Activity.RESULT_OK){
f = newFile(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("image.png")) {
f = temp;
imagePath= f.getAbsolutePath();
Bitmap thumbnail= BitmapFactory.decodeFile(f.getAbsolutePath(), options);
imgView.setImageBitmap(thumbnail);
}
You can fetch image from path "imagePath" whenever you have to display it.
Post a Comment for "How To Take A Picture To Show In A `imageview` And Save The Picture?"