Android: How to display video thumbnail in ImageView? - android

I have browsed around and tried multiple suggestions for how to display a recorded video to an ImageView without success.
This code works fine for taking an image and having the image displayed. The video also is recorded and saved to the phone, but it won't show up in the ImageView. Any suggestions on how I can modify my code here to have the Video appear in the ImageView?
Everything seems to work fine besides the: RESULT_LOAD_VID section, which should be displaying the selected or recorded video to the ImageView.
The error I receive is: "SkImageDecoder::Factory returned null"
From what I understand this means that for whatever reason the selected/recorded videos location isn't getting passed on to the RESULT_LOAD_VID section.
Any help is appreciated.
Here is my current code:
public class Media extends AppCompatActivity{
private static int RESULT_LOAD_IMG = 1;
private static int RESULT_LOAD_VID = 1;
String imgDecodableString;
private String selectedImagePath = "";
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
final private int CAPTURE_IMAGE = 2;
private Uri fileUri;
private ImageView mImageView;
Toolbar toolbar;
private String imgPath;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbarmedia, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
AlertDialog.Builder builder = new AlertDialog.Builder(Media.this);
// builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Take a Photo", "Choose from Gallery" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
break;
default:
break;
}
}
});
builder.show();
return true;
case R.id.video:
AlertDialog.Builder builder2 = new AlertDialog.Builder(Media.this);
// builder.setTitle("Choose Image Source");
builder2.setItems(new CharSequence[]{"Take a Video", "Select Video from Phone"},
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
//create new Intent
Intent intent_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video
intent_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent_video.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent_video, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
break;
case 1:
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_VID);
break;
default:
break;
}
}
});
builder2.show();
return true;
case R.id.mic:
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mImageView = (ImageView) findViewById(R.id.media_display);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.media_display);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
System.out.println("path" + selectedImagePath);
mImageView.setImageBitmap(decodeStream(selectedImagePath));
} else if(requestCode == RESULT_LOAD_VID && resultCode == RESULT_OK && null != data){
// Get the Image from data
Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
//Get the cursor
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView vidView = (ImageView) findViewById(R.id.media_display);
// Set the Image in ImageView after decoding the String
vidView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}else if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video Saved to Phone", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
Toast.makeText(this, "Video capture failed.",
Toast.LENGTH_LONG).show();
super.onActivityResult(requestCode, resultCode, data);
}
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public Bitmap decodeStream(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;
}
}

If you have path of your video file then use this method to create thumbnail in bitmap format.
public Bitmap createVideoThumbNail(String path){
return ThumbnailUtils.createVideoThumbnail(path,MediaStore.Video.Thumbnails.MICRO_KIND);
}
and use it in your image view like:-
ivVideoThumbnail.setImageBitmap(createVideoThumbNail(videoPath));

This should work fine
bitmap = ThumbnailUtils.createVideoThumbnail(file, new Size(100, 100), null);
imageview.setImageBitmap(bitmap);

Related

Capturing and storing multiple images in android [duplicate]

I seem to be having trouble creating a Bitmap from fileUri.
I would like to be able to set this Bitmap to an Imageview for previewing the image, and later adding elements to the image.
Any ideas why the image does not get set properly?
public class FeedActivity extends Fragment implements OnClickListener {
ImageView m_ImageView;
ImageButton btnCamera, btnGallery;
private final String TAG_CAMERA_FRAGMENT = "camera_fragment";
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_feed, container, false);
m_ImageView = (ImageView) view
.findViewById(R.id.imageViewFeed);
btnCamera = (ImageButton) view.findViewById(R.id.btn_Camera);
btnCamera.setOnClickListener(this);
btnGallery = (ImageButton) view.findViewById(R.id.btn_Gallery);
btnGallery.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_Camera:
Log.e("CAMERA", "CAMERA BUTTON PRESSED");
takePicture();
break;
case R.id.btn_Gallery:
Log.e("Gallery", "GALLERY BUTTON PRESSED");
break;
}
}
public void takePicture() {
// create Intent to take a picture and return control to the calling
// application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_OK----------------");
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
m_ImageView.setImageBitmap(bitmap);
// Bundle bundle = new Bundle();
// bundle.putParcelable("URI", fileUri);
//
// Fragment fragment = new PictureEditActivity();
// fragment.setArguments(bundle);
//
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.contentFragment, fragment,
// TAG_CAMERA_FRAGMENT).commit();
if (fileUri != null) {
Log.e("CAMERA", "Image saved to:\n" + fileUri);
Log.e("CAMERA", "Image path:\n" + fileUri.getPath());
}
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.e("ONACTIVITYRESULT",
"-----------------RESULT_CANCELLED----------------");
} else {
}
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Pixagram");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Pixagram", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
It appears as if I have found a solution.
http://www.androidhive.info/2013/09/android-working-with-camera-api/
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
m_ImageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}

Why can't some images be displayed on ImageView (Android)?

When I pick an image from my gallery, screenshots are shown but some images taken from camera aren't shown.
To be more specific, images taken using the system Camera app can't be shown while the ones taken using Camera360 can.
I wonder if there's any problem with my code. If there isn't, maybe it's because of my phone?
Thanks in advance. Sorry, my English isn't very good.
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
img = (ImageView) findViewById(R.id.ImageView01);
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
Drawable image;
try {
InputStream inputStream = getContentResolver()
.openInputStream(selectedImageUri);
image = Drawable.createFromStream(inputStream, "file///"
+ selectedImagePath.toString());
} catch (FileNotFoundException e) {
image = getResources().getDrawable(R.drawable.ic_launcher);
}
img.setImageDrawable(null);
img.setImageDrawable(image);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Oh, I found the problem. My image is too large. Updated code with several improvements below:
private static Context context;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int SELECT_PICTURE = 3;
private String selectedImagePath;
private static String imageFilePath;
private static String videoFilePath;
private Uri fileUri;
private Bitmap bitmap;
private Button btnGallery, btnCamera;
private Intent selectPictureIntent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
context = this;
btnGallery = (Button) findViewById(R.id.Button01);
btnCamera = (Button) findViewById(R.id.Button02);
btnGallery.setOnClickListener(this);
btnCamera.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
Log.d("bitmap", selectedImageUri.getScheme());
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
// Selected image is local image
Bitmap b = new BitmapDrawable(context.getResources(),
selectedImagePath).getBitmap();
int i = (int) (b.getHeight() * (512.0 / b.getWidth()));
bitmap = Bitmap.createScaledBitmap(b, 512, i, true);
} else {
// Selected image is Picasa image
loadPicasaImageFromGallery(selectedImageUri);
}
ImageView img = (ImageView) findViewById(R.id.ImageView01);
img.setImageBitmap(bitmap);
}
}
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
addImageToGallery(imageFilePath, context);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
addVideoToGallery(videoFilePath, context);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
public Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor = getContentResolver()
.openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor
.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else
return uri.getPath();
}
private void loadPicasaImageFromGallery(final Uri uri) {
String[] projection = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
if (columnIndex != -1) {
new Thread(new Runnable() {
// NEW THREAD BECAUSE NETWORK REQUEST WILL BE MADE THAT WILL
// BE A LONG PROCESS & BLOCK UI
// IF CALLED IN UI THREAD
public void run() {
try {
Bitmap bm = android.provider.MediaStore.Images.Media
.getBitmap(getContentResolver(), uri);
int i = (int) (bm.getHeight() * (512.0 / bm
.getWidth()));
bitmap = Bitmap
.createScaledBitmap(bm, 512, i, true);
// THIS IS THE BITMAP IMAGE WE ARE LOOKING FOR
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
}
cursor.close();
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MappyDiary");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MappyDiary", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
imageFilePath = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
mediaFile = new File(imageFilePath);
} else if (type == MEDIA_TYPE_VIDEO) {
videoFilePath = mediaStorageDir.getPath() + File.separator + "VID_"
+ timeStamp + ".mp4";
mediaFile = new File(videoFilePath);
} else {
return null;
}
return mediaFile;
}
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);
}
public static void addVideoToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Video.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Button01:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
selectPictureIntent = Intent
.createChooser(intent, "Select Picture");
startActivityForResult(selectPictureIntent, SELECT_PICTURE);
break;
case R.id.Button02:
// create Intent to take a picture and return control to the calling
// application
Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent2.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent2, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
default:
break;
}
}

How I can resize images taken from the Gallery?

I'm trying to:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, RESULTADO_GALERIA);
.
.
.
String imgPath = data.getDataString(); // return something like "/external/images/media/13852"
BitmapFactory.decodeFile(imgPath); // allways null...
I also tried:
File bitmapFile = new File(Environment.getExternalStorageDirectory()
+ "/" + imgPath);
String aux = bitmapFile.getAbsolutePath(); // /storage/sdcard0/external/images/media/13852
BitmapFactory.decodeFile(bitmapFile.getAbsolutePath()); // NULL
An the result it's the same
The olny thing work's for me is put the path manually...
File file = new File("/storage/sdcard0/DCIM/Camera/"+"IMG_20140506_101341.jpg"); // nothing to do with the path obtained by code...
BitmapFactory.decodeFile(bitmapFile.getAbsolutePath()); // OK
How can I get the REAL path for a image of the gallery? Other ideas to resize them?
Thanks!
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;
}

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;
}

I want to make a Dialog Screen Like WhatsApp Profile Photo Dialog Screen

hello Friends....
I am currently trying to make a Dialog using Implicit Intent where i want to show my Dialog like whatsApp(Profile Photo Screen) and in this screen whatsApp are using extra field named as "Remove Photo". When i try to make same type of screen Dialog then i am unable to add this extra field("Remove Photo"). i have done all code. its working fine for three option in Dialog like(Gallery,Photo,Camera) and i am unable to handle these all in onActivityResult() . I am sending my all source code i have tried much hard , but i am not able to find the solution to do so. plz..... friends help me out from this.
In this code i am simply create a method named as openFileChooser() in which i have write all the code for creating Dialog Screen and handle this outcomes in onActivityResult()
Here Is my code
ProfilePhotoActivity.java
public class ProfilePhotoActivity extends Activity implements OnClickListener{
ImageButton back, editPhoto, selectAction;
ImageView imgCamera;
private static final int FILECHOOSER_RESULTCODE = 2888;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Uri mCapturedImageURI = null;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_profilephoto);
back=(ImageButton)findViewById(R.id.btn_back);
editPhoto=(ImageButton)findViewById(R.id.ibEditPhoto);
selectAction=(ImageButton)findViewById(R.id.ibSelectAction);
imgCamera=(ImageView)findViewById(R.id.imvProfilePhoto);
editPhoto.setOnClickListener(this);
selectAction.setOnClickListener(this);
back.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_back:
ProfilePhotoActivity.this.finish();
break;
case R.id.ibEditPhoto:
openFileChooser(null, null);
// startDialog();
break;
case R.id.ibSelectAction:
break;
}
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
try{
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_PICK);
// i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Exception:"+e,
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (requestCode == GALLERY_PICTURE)
{
if (resultCode == RESULT_OK)
{
if (intent != null)
{
// our BitmapDrawable for the thumbnail
BitmapDrawable bmpDrawable = null;
// try to retrieve the image using the data from the intent
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
Bitmap galleryBitmap = BitmapFactory.decodeFile(fileSrc); // load preview image
galleryBitmap = Bitmap.createScaledBitmap(galleryBitmap, 200, 200, true);
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/TimeChat/image/"+System.currentTimeMillis()+".jpg";
//imgCamera.setRotation(0);
imgCamera.setImageBitmap(galleryBitmap);
// writeToFile(filePath, galleryBitmap);
}
else
{
bmpDrawable = new BitmapDrawable(getResources(), intent.getData().getPath());
imgCamera.setImageDrawable(bmpDrawable);
}
}
else
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
else if (requestCode == CAMERA_REQUEST)
{
if (resultCode == RESULT_OK)
{
if (intent.hasExtra("data"))
{
// retrieve the bitmap from the intent
Bitmap cameraBitmap = (Bitmap) intent.getExtras().get("data");
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/TimeChat/image/"+System.currentTimeMillis()+".jpg";
// update the image view with the bitmap
imgCamera.setImageBitmap(cameraBitmap);
// writeToFile(filePath, circleBitmap);
}
else if (intent.getExtras() == null) {
Toast.makeText(getApplicationContext(), "No extras to retrieve!", Toast.LENGTH_SHORT).show();
BitmapDrawable thumbnail = new BitmapDrawable(getResources(), intent.getData().getPath());
// update the image view with the newly created drawable
imgCamera.setImageDrawable(thumbnail);
}
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
ProfilePhotoActivity.this.finish();
}
}
This looks like it will be a problem:
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (requestCode == GALLERY_PICTURE)
unless FILECHOOSER_RESULTCODE and GALLERY_PICTURE are the same ints then statement will never pass.
It may be possible to use request code to distinguish between "types" of photos i.e.
protected static final int MY_FACE_PHOTO = 0;
protected static final int MY_CAR_PHOTO = 1;
protected static final int MY_HOUSE_PHOTO = 2;
And you may use Intent.putExtra(String name, String value) when you create Intents before starting new activity, like:
#NonNls protected static final String STRING_EXTRA = "string_extra";
#NonNls protected static final String CAMERA = "camera";
#NonNls protected static final String GALLERY = "gallery";
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
cameraIntent.putExtra(STRING_EXTRA, CAMERA);
galleryIntent.putExtra(STRING_EXTRA, GALLERY)
startActivityForResult(takePicture,
MY_FACE_PHOTO /* put here your desired request code */)
After that in onActivityResult() method you may use them:
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(intent != null)
{
if(resultCode == Activity.RESULT_OK)
{
String extraString = intent.getStringExtra(STRING_EXTRA);
if(extraString.equals(CAMERA))
{
// ... i. e.
switch (requestCode)
{
case MY_FACE_PHOTO:
{
// ...
break;
}
case MY_CAR_PHOTO:
{
// ...
break;
}
case MY_HOUSE_PHOTO:
{
// ...
break;
}
default:
{
// ...
break;
}
}
}
else if(extraString.equals(GALLERY))
{
// ...
}
}
else
{
// ...
}
}
}

Categories

Resources