Picture does not show in imageview - android

I am opening camera on button click and taking picture and showing it in imageview. It's working in Google Nexus. But it's not working in Samsung Tab and Micromax canvas HD,Why?
My Button click code :
CAMERA_PIC_REQUEST = 100;
String path = Environment.getExternalStorageDirectory()
+ "/MySampleApp/image.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
OnActivityResult code :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(path,
options);
mImageView.setImageBitmap(bitmap);
Permissions in manifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
Why is this code not working in samsung and micromax?
This is the correct code are not?
Any one please help me?

Try this
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0)
{
CAMERA_PIC_REQUEST = 100;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
And
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(photo);
}
}

Try this code it will work in micromax devices..use this uri
btnGallery.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
pop.dismiss();
startActivityForResult(Intent.createChooser(intent, "Select Picture"), StaticMembers.galleryRequestCode);
}
});
ImageView btnCamera = (ImageView) pop.findViewById(R.id.ivCamera);
btnCamera.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//With Camera Utils
pop.dismiss();
outpuUri = CameraUtil.startCam(yourActivity.this);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d("Alpha", "onActivity : " + requestCode);
System.gc();
Log.d("Alpha", "onActivity : " + requestCode + " RESULT CODE : " + resultCode);
System.gc();
long timestamp = System.currentTimeMillis() / 1000L;
String time = timestamp + "";
String imgPath = null;
if (requestCode == CameraUtil.IMAGE_CAPTURED && resultCode == Activity.RESULT_OK)
{
if (outpuUri != null)
{
Log.d("Alpha", "URI NOT NULL");
imgPath = outpuUri.getPath();
//Log.d("Alpha", "ACT RES PATH : " + imgPath);
//mCapturedBitmap = CameraUtil.sampleBitmap(imgPath, ivHeightWidth);
//iv.setImageBitmap(mCapturedBitmap);
}
else
{
Log.d("Alpha", "URI NULL IN CAM");
}
}
else if (requestCode == StaticMembers.galleryRequestCode && resultCode == Activity.RESULT_OK)
{
outpuUri = data.getData();
imgPath = getPath(outpuUri);
mCapturedBitmap = CameraUtil.sampleBitmap(imgPath, ivHeightWidth);// BitmapFactory.decodeFile(imgPath);
iv.setImageBitmap(mCapturedBitmap);
Log.d("Alpha", "In Gallery " + imgPath);
}
if (imgPath != null)
{
showConfrirmDialog(imgPath, time);
}
}
public class CameraUtil
{
private static Uri outpuUri;
public static final int IMAGE_CAPTURED = 200;
public static String imageName;
private static String imageFolder;
public static Uri startCam(Activity context)
{
imageName = "sample" + System.currentTimeMillis() + ".jpg";
outpuUri = Uri.fromFile(new File(getImageFolderFile().getAbsolutePath() + File.separator + imageName));
Log.d("CHECK", "BEFORE STARTING CAM URI : " + outpuUri.getPath());
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, outpuUri);
i.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
context.startActivityForResult(i, IMAGE_CAPTURED);
return outpuUri;
}
public static File getImageFolderFile()
{
imageFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sparkchat_camera_pics";
File f = new File(imageFolder);
Log.d("Alpha", f.getAbsolutePath() + " exists > " + f.exists());
if (!f.exists())
f.mkdirs();
return f;
}
}

Related

Android onclick radio button camera intent not working

i have a radio button. when i click on radio button camera intent is opened after taking a image using camera. image is not updating to image view.
i have used all permissions in my manifest file.
RB_PhotoStatus
.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
switch (checkedId) {
case R.id.yes:
//photoCollected = "Yes";
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
break;
case R.id.no:
photoCollected = "No";
break;
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(bp);
}
Taking Photos Simply!
This answer explains how to capture photos using an existing camera application.
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
Request for camera application.
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
Camera return intent with data on Activity override function onActivityResult as bellow:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
For more info follows this link given bellow:
http://developer.android.com/training/camera/photobasics.html
It doesn't work because Camera Intent won't return the entire BitMap, but only the reference (Uri) to the created file.
Uri selectedImage = data.getData();
From this Uri you may re-load the BitMap using BitmapFactory.decodeFile
On radiobuttonclick();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
onActivityResult();
Uri originalUri = data.getData();
imageview.setImageURI(originalUri);
And If you want to get bitmap then
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), originalUri);
private String mCurrentPhotoPath;
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
final File image = create_directory();
// Save a file: path for use with ACTION_VIEW intents
try {
mCurrentPhotoPath = image.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (image != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
snackbar = Snackbar.make(findViewById(android.R.id.content), "An error has occurred", Snackbar.LENGTH_SHORT);
snackbar.setAction("Dismiss", clickListener);
snackbar.show();
}
}
}
public File create_directory() {
// Create an image file name
final String imageFileName;
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
final String user_id = "1_";
imageFileName = user_id + timeStamp + "_";
final String proj_name = "test";
final String folder_timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).format(new Date());
final String path = "/TEST/" + proj_name + "/" + folder_timeStamp;
final File dr = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), path);
if (!dr.exists()) {
dr.mkdirs();
}
File image = null;
try {
image = File.createTempFile(imageFileName, ".jpg", dr);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
//do something with the image which is stored in mCurrentPhotoPath
}
}
}

Android "TAKE PHOTO" - Image which is clicked is getting saved as a corrupt image

I have a button, which opens up a dialog box asking user to either "Take Picture" or "Choose from gallery".
I am facing issues when user "Take photo" , image is getting clicked, and for verification purpose I am setting Bitmap image inside the circularImage view, but when I go to specified location path of the image, either Image is not there or Image is corrupted.
Also I am trying to upload the image to the server using AsyncHttpClient in android but not being able to do it successfully.
Everytime I am getting Java Socket TimeOut Exception.
Below is the code for my Camera Intent Activity
public class AddAnUpdateActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.composeEditText = (EditText) findViewById(R.id.composeEditText);
setContentView(R.layout.add_update);
ProfilePictureImage = (CircularImageView) findViewById(R.id.ProfilePic);
insertVideo = (ImageButton) findViewById(R.id.insertVideoButton);
setBtnListenerOrDisable(insertVideo,mTakeVidOnClickListener, MediaStore.ACTION_VIDEO_CAPTURE);
insertImage = (ImageButton) findViewById(R.id.insertImageButton);
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void setBtnListenerOrDisable(ImageButton btn,
Button.OnClickListener onClickListener,
String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setClickable(false);
}
}
private boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddAnUpdateActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if(options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("Assert")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
Log.d("PhotoImage","file path:"+f);
Log.d("PhotoImage","list of file path:"+ Arrays.toString(f.listFiles()));
for (File temp : f.listFiles()) {
if (temp.getName().equals("Image.jpg")) {
Log.w("PhotoImage","enter in if block");
f = temp;
break;
}
}
try {
Log.w("PhotoImage","enter in else block");
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
if(bitmap!=null)
{
bitmap.recycle();
bitmap=null;
}
String path = android.os.Environment.getExternalStorageDirectory()+ File.separator+ "Pictures" + File.separator + "Screenshots";
Log.w("PhotoImage","path where the image is stored :"+path);
setFilePath(path);
f.delete();
OutputStream outFile;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
Log.w("PhotoImage","file value:"+String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
setFilePath(picturePath);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.d("PhotoImage path of image from gallery......******************.........", picturePath + "");
ProfilePictureImage.setImageBitmap(thumbnail);
}
else if(requestCode == 3){
handleCameraVideo(data) ;
}
}
}
private void handleCameraVideo(Intent data) {
VideoUri = data.getData();
VideoView.setVideoURI(VideoUri);
//mImageBitmap = null;
} }
private void startActivityFeedActivity() {
Intent i = new Intent(getApplicationContext(), ActivityFeedActivity.class);
startActivity(i);
}
}
I simplified your code .keep reference of file path global
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "Image.jpg");
globalpath =f.getAbsolutePath(); //String make it global
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
//your onactivityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File myfile = new File(globalpath);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(myfile.getAbsolutePath(),
bitmapOptions);
ProfilePictureImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "Screenshots";
OutputStream outFile;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
myfile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Depending on your Android version and device, the camera intent is to be implemented differently. Check out https://github.com/ralfgehrer/AndroidCameraUtil. The code is tested on 100+ devices.
After take the photo remember to use this:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
to scan the media file in your gallery. If you doesn't do it your photo will appear after some time. You can do it in onClick:
insertImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
}
});

Camera Intent returned Null value

i am creating an application using camera. The intent returns null value in samsung mobile. but it is perfectly working in sony mobile. i don't know whats problem in that.My code is here.
Intent cameraIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
Log.i("mediaFile",""+mediaFile);
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE&& resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
Toast.makeText(this, capturedImageFilePath, Toast.LENGTH_SHORT).show();
}
File sdImageMainDirectory = new File(root, ActivityConst.ENCYIMAGE);
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_CAPTURE);
I am following this in my app its working fine
I have demonstrate to Both the case
1) capture Photo from camera
2) Take a photo from gallary
Try this is working like charm with me
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
btnGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}

user Intent send image path to another Activity

sometime i running App on my phone.problem is when i click Ok button after camera was pick photo up,at this moment!App' stop running!in fact,i wanna see Pic on another Activity!Is
take picture:
private void takePhoto() {
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues();
photoUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getActivity(), R.string.take_photo_rem,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), R.string.takePhoto_msg,
Toast.LENGTH_LONG).show();
}
}
album:
private void pickPhoto() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
}
onActivityResult: user intent send image uri
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
doPhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doPhoto(int requestCode, Intent data) {
if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
if (data == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if (photoUri == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
}
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try {
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, "error:" + e);
}
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null) {
Intent startEx = new Intent(getActivity(), PhotoPre.class);
Bundle bundle = new Bundle();
bundle.putString(SAVED_IMAGE_DIR_PATH, picPath);
startEx.putExtras(bundle);
startActivity(startEx);
} else {
Toast.makeText(getActivity(), R.string.photo_err, Toast.LENGTH_LONG)
.show();
}
}
preview image Activity!is getIntent() seted null?
Bundle bundle = getIntent().getExtras();
picPath = bundle.getString(KEY_PHOTO_PATH);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bm = BitmapFactory.decodeFile(picPath, options);
1 - start camera for take image
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment .getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, Const.dbSrNo + "image.jpg");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
2 - write below code in "onActivityResult"
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
File imgFile = new File(Environment.getExternalStorageDirectory(),
"/MyImages/");
/*photo = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg");*/
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable=true;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg",options);
imageView2.setImageBitmap(bm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byteImage_photo = baos.toByteArray();
Const.imgbyte=byteImage_photo;
3 - generate one java file Const.java
public class Const {
public static byte[] imgbyte = "";
}
4 - now display that image in your activity using
byte[] mybits=Const.imgbyte;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(mybits, 0, mybits.length, options);
yourImageview.setImageBitmap(bitmap);

How to see camera app take photo asynchronous in the gallery

I am working on a basic camera app. I can take a photo, and I can see it in my app. But I want to see my photo in gallery asynchronous. When restart the phone, I can see my photo in the gallery.
Sample code.
public class PhotosActivity extends Fragment implements View.OnClickListener {
private final int REQUEST_CODE = 100;
private Button fotobutton;
private ImageView foto_image;
private static final String IMAGE_DIRECTORY_NAME = "OlkunMustafa";
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
// Directory name to store captured images and videos
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos_activity,container,false);
fotobutton = (Button) rootView.findViewById(R.id.fotobutton);
foto_image = (ImageView) rootView.findViewById(R.id.foto_image);
fotobutton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if( v == fotobutton) {
Intent photo_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
photo_intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(photo_intent,100);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK)
{
BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
foto_image.setImageBitmap(bitmap);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
private static Uri getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStorageDirectory(),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
else {
return null;
}
return Uri.fromFile(mediaFile);
}
}
How can I do it?
You need to call a broadcast to tell Android OS that you have added an Image
First Method
private void galleryAddPic()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
Second Method
Or Call
ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
Also have a look on this answer
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
And ScanListener
You can directly save image to Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Try using this logic :
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}

Categories

Resources