I have an activity wherin I give the user an option to click an image from the camera, then I store this image in a byte array and in the Database. However my code does not seem to work on Samsung Galaxy S3 below is the code:
Camera calling intent:
if (i == 0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
On Activity method for the camera:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1337 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
thumbnail = (Bitmap) extras.get("data");
image(thumbnail);
} else {
Toast.makeText(CreateProfile.this, "Picture NOt taken", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
My image(Bitmap thumbnail) function:
public void image(Bitmap thumbnail) {
Bitmap photo = thumbnail;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
b = bos.toByteArray();
ImageView imageview = (ImageView)findViewById(R.id.imageView1);
Bitmap bt = Bitmap.createScaledBitmap(photo, 100, 80, false);
imageview.setImageBitmap(bt);
}
However this was not working with Samsung S3, I changed the code to the following and now it works with Samsung S3, however it does not work with any other device.
Camera Intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Activity for result:
startActivityForResult(intent, CAMERA_IMAGE_CAPTURE);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
// Describe the columns you'd like to have returned. Selecting from the Thumbnails location gives you both the Thumbnail Image ID, as well as the original image ID
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA};
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select only mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
//At the moment, this is a bit of a hack, as I'm returning ALL images, and just taking the latest one. There is a better way to narrow this down I think with a WHERE clause which is currently the selection variable
Cursor myCursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try{
myCursor.moveToFirst();
imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
}
finally{myCursor.close();}
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try{
myCursor.moveToFirst();
//This will actually give yo uthe file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
}
finally{myCursor.close();}
// These are the two URI's you'll be interested in. They give you a handle to the actual images
Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the URI's to my own objects anyways...
// Toast.makeText(this, ""+largeImagePath, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriLargeImage, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriThumbnailImage, Toast.LENGTH_LONG).show();
if (largeImagePath != null) {
// Toast.makeText(this, "" + largeImagePath, Toast.LENGTH_LONG).show();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
// thumbnail = (BitmapFactory.decodeFile(picturePath));
thumbnail = BitmapFactory.decodeFile((largeImagePath), opts);
System.gc();
if (thumbnail != null) {
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
}
image(thumbnail);
}
if (uriLargeImage != null) {
Toast.makeText(this, "" + uriLargeImage, Toast.LENGTH_LONG).show();
}
if (uriThumbnailImage != null) {
Toast.makeText(this, "" + uriThumbnailImage, Toast.LENGTH_LONG).show();
}
}
This is my image() function:
public void image(Bitmap thumbnail) {
b = null;
Bitmap photo = thumbnail;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
b = bos.toByteArray();
if (b != null) {
Toast.makeText(this, "Success Yeah" + b, Toast.LENGTH_LONG).show();
}
}
While as all the three 1)uriLargeImage 2)largeImagePath 3)uriThumbnailImage return me the path or URI I am unable to set the created bitmap to my ImageView. However this is the case with Samsung S3 only, if I run the above edited code with any other device, the program crashes.
In the manifest I have used
android:configChanges="keyboardHidden|orientation"
Based on the tutorial: http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/
However if I take the picture in Landscape mode, everything works fine! I am puzzled!! (In Samsung S3)
Finally after struggling for three days, I have devised a simple mechanism to overcome the Samsung S3 Saga.
Below is the code, a quick summary of the code is that I first check the Manufacturer of the device and based on this I call different intents for camera.
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
private static final int PICK_FROM_GALLERY = 2;
int CAMERA_PIC_REQUEST = 1337;
Bitmap thumbnail = null;
private static final int OG = 4;
private static final int CAMERA_IMAGE_CAPTURE = 0;
Uri u;
ImageView imgview;
// int z=0;
String z = null;
byte b[];
String largeImagePath = "";
Uri uriLargeImage;
Uri uriThumbnailImage;
Cursor myCursor;
public void imageCam(Bitmap thumbnail) {
Bitmap photo = thumbnail;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 70, bos);
b = bos.toByteArray();
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
imageview.setImageBitmap(photo);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(onBTN);
if (savedInstanceState != null) {
Bitmap Zatang;
String B1 = savedInstanceState.getString("message");
Toast.makeText(this, "SavedYeah" + B1, Toast.LENGTH_LONG).show();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
Zatang = BitmapFactory.decodeFile((B1), opts);
System.gc();
if (Zatang != null) {
Toast.makeText(this, "Success Zatang" + B1, Toast.LENGTH_LONG)
.show();
imageCam(Zatang);
}
}
}
private View.OnClickListener onBTN = new View.OnClickListener() {
public void onClick(View v) {
openNewGameDialog();
}
};
String[] B = { "Cam", "Gallery" };
private void openNewGameDialog() {
new AlertDialog.Builder(this).setItems(B,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,int i) {
if (i == 0) {
String BX1 = android.os.Build.MANUFACTURER;
if(BX1.equalsIgnoreCase("samsung")) {
Toast.makeText(getApplicationContext(), "Device man"+BX1, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_IMAGE_CAPTURE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
} else if (i == 1) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
}).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_IMAGE_CAPTURE && resultCode==Activity.RESULT_OK){
// Describe the columns you'd like to have returned. Selecting from the Thumbnails location gives you both the Thumbnail Image ID, as well as the original image ID
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA};
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select only mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
//At the moment, this is a bit of a hack, as I'm returning ALL images, and just taking the latest one. There is a better way to narrow this down I think with a WHERE clause which is currently the selection variable
myCursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
myCursor.close();
}
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
largeImagePath = "";
try {
myCursor.moveToFirst();
//This will actually give yo uthe file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
myCursor.close();
}
// These are the two URI's you'll be interested in. They give you a handle to the actual images
uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the URI's to my own objects anyways...
// Toast.makeText(this, ""+largeImagePath, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriLargeImage, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriThumbnailImage, Toast.LENGTH_LONG).show();
if (largeImagePath != null) {
Toast.makeText(this, "LARGE YES"+largeImagePath, Toast.LENGTH_LONG).show();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
thumbnail = BitmapFactory.decodeFile((largeImagePath), opts);
System.gc();
if (thumbnail != null) {
Toast.makeText(this, "Try Without Saved Instance", Toast.LENGTH_LONG).show();
imageCam(thumbnail);
}
}
if (uriLargeImage != null) {
Toast.makeText(this, ""+uriLargeImage, Toast.LENGTH_LONG).show();
}
if (uriThumbnailImage != null) {
Toast.makeText(this, ""+uriThumbnailImage, Toast.LENGTH_LONG).show();
}
}
if( requestCode == 1337 && resultCode== RESULT_OK){
Bundle extras = data.getExtras();
if (extras.keySet().contains("data") ){
BitmapFactory.Options options = new BitmapFactory.Options();
thumbnail = (Bitmap) extras.get("data");
if (thumbnail != null) {
Toast.makeText(this, "YES Thumbnail", Toast.LENGTH_LONG).show();
BitmapFactory.Options opt = new BitmapFactory.Options();
thumbnail = (Bitmap) extras.get("data");
imageCam(thumbnail);
}
} else {
Uri imageURI = getIntent().getData();
ImageView imageview = (ImageView)findViewById(R.id.imageView1);
imageview.setImageURI(imageURI);
if(imageURI != null){
Toast.makeText(this, "YES Image Uri", Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options opts = new BitmapFactory.Options();
thumbnail = BitmapFactory.decodeFile((picturePath), opts);
System.gc();
imageCam(thumbnail);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("message",largeImagePath );
}
}
}
Above ans with some correction for normal samsung device and orientaton issue problem
private void cameraIntent() {
new AlertDialog.Builder(this).setItems(B,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,int i) {
if (i == 0) {
String manufacturer_Type = android.os.Build.MANUFACTURER;
if(manufacturer_Type.equalsIgnoreCase("samsung")) {
Toast.makeText(getApplicationContext(), "Device man"+manufacturer_Type, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_IMAGE_CAPTURE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
} else if (i == 1) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
}
}).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_IMAGE_CAPTURE && resultCode==Activity.RESULT_OK){
// Describe the columns you'd like to have returned. Selecting from the Thumbnails location gives you both the Thumbnail Image ID, as well as the original image ID
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA};
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select only mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
//At the moment, this is a bit of a hack, as I'm returning ALL images, and just taking the latest one. There is a better way to narrow this down I think with a WHERE clause which is currently the selection variable
myCursor = CameraActivity.this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
int cursor_size = myCursor.getCount();
if(cursor_size>0){
myCursor.moveToFirst();
imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
myCursor.close();
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor mCursor = CameraActivity.this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
largeImagePath = "";
try {
mCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
}finally{
mCursor.close();
}
// These are the two URI's you'll be interested in. They give you a handle to the actual images
uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the URI's to my own objects anyways...
// Toast.makeText(this, ""+largeImagePath, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriLargeImage, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriThumbnailImage, Toast.LENGTH_LONG).show();
if (largeImagePath != null) {
Toast.makeText(this, "LARGE YES"+largeImagePath, Toast.LENGTH_LONG).show();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
thumbnail = BitmapFactory.decodeFile((largeImagePath), opts);
System.gc();
if (thumbnail != null) {
Toast.makeText(this, "Try Without Saved Instance", Toast.LENGTH_LONG).show();
Bitmap rotatedImage = exifImage(thumbnail, largeImagePath);
// imageCam(thumbnail);
if(imageview!=null){
imageview.setImageBitmap(rotatedImage);
}
}
}
if (uriLargeImage != null) {
Toast.makeText(this, ""+uriLargeImage, Toast.LENGTH_LONG).show();
}
if (uriThumbnailImage != null) {
Toast.makeText(this, ""+uriThumbnailImage, Toast.LENGTH_LONG).show();
}
}else{
requestCode=CAMERA_SAMSUNG_NORMAL_PIC_REQUEST;
normalDeviceCamera(requestCode, resultCode, data);
}
} catch(Exception e){
e.printStackTrace();
}finally {
if(!myCursor.isClosed()){
myCursor.close();
}
}
}
if( requestCode == CAMERA_PIC_REQUEST && resultCode== RESULT_OK){
normalDeviceCamera(requestCode, resultCode, data);
}
}
private void normalDeviceCamera(int requestCode, int resultCode, Intent data){
if( requestCode == CAMERA_PIC_REQUEST && resultCode== RESULT_OK){
Bundle extras = data.getExtras();
if (extras.keySet().contain`enter code here`s("data") ){
BitmapFactory.Options options = new BitmapFactory.Options();
thumbnail = (Bitmap) extras.get("data");
if (thumbnail != null) {
Toast.makeText(this, "YES Thumbnail", Toast.LENGTH_LONG).show();
/* BitmapFactory.Options opt = new BitmapFactory.Options();*/
thumbnail = (Bitmap) extras.get("data");
if(imageview!=null){
imageview.setImageBitmap(thumbnail);
}
}
} else {
Uri imageURI = getIntent().getData();
// ImageView imageview = (ImageView)findViewById(R.id.imgCam);
if(imageview!=null){
imageview.setImageURI(imageURI);
}
if(imageURI != null){
Toast.makeText(this, "YES Image Uri", Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Related
I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
This is Image feathing method
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(AddServiceActivity.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 cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 100);
} 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, 10);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
This is OnActivityResult code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (data.getData() != null) {
selectedImageUri = data.getData();
} else {
Log.d("selectedPath1 : ", "Came here its null !");
Toast.makeText(getApplicationContext(), "failed to get Image!", Toast.LENGTH_SHORT).show();
}
if (requestCode == 100 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
selectedPath = getPath(selectedImageUri);
camera.setImageURI(selectedImageUri);
Log.d("selectedPath1 : ", selectedPath);
getimage(selectedImageUri);
}
if (requestCode == 10)
{
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);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from ", picturePath + "");
camera.setImageBitmap(thumbnail);
getimage(selectedImage);
}
}
}
Image changing code id here
private void getimage(final Uri uri) {
Bitmap image = null;
WeakReference<Bitmap> weakReference = new WeakReference<Bitmap>(new BitmapDrawable(getResources(), uri.getPath()).getBitmap());
int nh = (int) (weakReference.get().getHeight() * (512.0 / weakReference.get().getWidth()));
image = Bitmap.createScaledBitmap(weakReference.get(), 512, nh, true);
Log.e("", "bitmap size is2:" + "" + nh + ":" + image.getByteCount());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e("", "encoded::" + encoded);
Log.d("", "encoded::" + encoded);
// user_imagebase64 = encoded;
try {
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the code is crashes in getimage method all time, when i call this method the app crashes at line
"int nh = (int) (weakReference.get().getHeight() * (512.0 / weakReference.get().getWidth()));"
and having error of Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getHeight()' on a null object reference
i dont know what the issue is and i can't use this code too..
I'm trying to write a small code that allows me to send picture directly after taking it from the camera, i want to send pict from capture in camera but never sucess, i'm always get message "Something went wrong"
There is the code
public void loadImagefromGallery(View view) {
CharSequence colors[] = new CharSequence[] {"Galery", "Foto"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfileActivity.this);
builder.setTitle("Pilih");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
} else if (which == 1) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if(requestCode == CAMERA_REQUEST){
Bitmap photo = (Bitmap) data.getExtras().get("data");
RoundedImageViewUtil imgView = (RoundedImageViewUtil) findViewById(R.id.profile);
imgView.setImageBitmap(photo);
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
RoundedImageViewUtil imgView = (RoundedImageViewUtil) findViewById(R.id.profile);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Intead of
Bitmap photo = (Bitmap) data.getExtras().get("data");
try
Uri imageUri = (Uri)data.getData();
and then from uri get your image bitmap.
Its been 5 days now and no one to help!! please can anyone help me
I have a problem and that persists specially for Samsumg S3 phones only.
I am trying to take 4 images from the Camera service of android.
The problem is when i am trying to do it for other phones the same code works perfectly fine, but shows problem with Samsung S3 phone.
What am i trying to do is have 4 Imageview's, on every imageview's onclick i can open camera service or gallery service according to the users choice. Once the image is being clicked or selected, that image is set on that particular imageview which was clicked.
So i can set all 4 images one by one. This works fine with other phone and also other samsung phones but seems to have a problem with Samsung S3.
Could anyone please help me out.
Here is my code where i am taking the images on the imageView.
My Oncreate method
public class Add_image extends Activity {
ImageView imgview1, imgview2, imgview3, imgview4;
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_IMAGE_CAPTURE = 0;
private static final int PICK_FROM_GALLERY = 2;
int CAMERA_PIC_REQUEST = 1337;
String SD_CARD_IMAGE_PATH = null;
byte b[];
String largeImagePath = "";
Uri uriLargeImage;
Uri uriThumbnailImage;
private static final int OG = 4;
int flag = 0, orientation;
String bal, picturePath, bal1, bal2, bal3, bal4;
int flagg = 0;
Cursor myCursor, cursor1;
Bitmap thumbnail = null;
TextView t5, t6, t7, t8;
// SharedPreferences pic1, pic2, pic3, pic4;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
imgview1 = (ImageView) this.findViewById(R.id.imageView1);
imgview1.setOnClickListener(click_img1);
imgview2 = (ImageView) this.findViewById(R.id.imageView2);
imgview2.setOnClickListener(click_img2);
imgview3 = (ImageView) this.findViewById(R.id.imageView3);
imgview3.setOnClickListener(click_img3);
imgview4 = (ImageView) this.findViewById(R.id.imageView4);
imgview4.setOnClickListener(click_img4);
t5 = (TextView) findViewById(R.id.textView5);
t5.setVisibility(View.VISIBLE);
t6 = (TextView) findViewById(R.id.textView6);
t6.setVisibility(View.VISIBLE);
t7 = (TextView) findViewById(R.id.textView7);
t7.setVisibility(View.VISIBLE);
t8 = (TextView) findViewById(R.id.textView8);
t8.setVisibility(View.VISIBLE);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(btn_click);
if (savedInstanceState != null) {
Bitmap carpic;
String B1 = savedInstanceState.getString("message");
// Toast.makeText(this, "SavedYeah"+B1, Toast.LENGTH_LONG).show();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
carpic = BitmapFactory.decodeFile((B1), opts);
System.gc();
if (carpic != null) {
imageCam(carpic);
}
}
}
different button clicks
public View.OnClickListener btn_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Add_image.this, Add.class);
startActivity(intent);
}
};
private View.OnClickListener click_img1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
openNewGameDialog();
}
};
private View.OnClickListener click_img2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 2;
openNewGameDialog();
}
};
private View.OnClickListener click_img3 = new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 3;
openNewGameDialog();
}
};
private View.OnClickListener click_img4 = new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 4;
openNewGameDialog();
}
};
My openNewGameDialog() method to check the Manufacturer and the Camera Service
String[] B = { "Camera", "Gallery", "Delete Image" };
private void openNewGameDialog() {
new AlertDialog.Builder(this).setItems(B,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
if (i == 0) {
String BX1 = android.os.Build.MANUFACTURER;
if (BX1.equalsIgnoreCase("samsung")) {
// Toast.makeText(getApplicationContext(),
// "Device man"+BX1, Toast.LENGTH_LONG).show();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
CAMERA_IMAGE_CAPTURE);
} else {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,
CAMERA_PIC_REQUEST);
}
}
else if (i == 1) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
} else if (i == 2) {
if (flag == 1) {
imgview1.setImageDrawable(null);
t5.setVisibility(View.VISIBLE);
}
if (flag == 2) {
imgview2.setImageDrawable(null);
t7.setVisibility(View.VISIBLE);
}
if (flag == 3) {
imgview3.setImageDrawable(null);
t6.setVisibility(View.VISIBLE);
}
if (flag == 4) {
imgview4.setImageDrawable(null);
t8.setVisibility(View.VISIBLE);
}
}
}
}).show();
}
imageCam() Method the set the Images to the ImageView
public void imageCam(Bitmap thumbnail) {
Bitmap photo = thumbnail;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 70, bos);
b = bos.toByteArray();
bal = Base64.encodeBytes(b);
// ImageView imageview = (ImageView) findViewById(R.id.imageView1);
String BX1 = android.os.Build.MANUFACTURER;
if (BX1.equalsIgnoreCase("samsung") && flagg == 0) {
}
if (flag == 1) {
bal1 = bal;
t5.setVisibility(View.GONE);
imgview1.setImageBitmap(photo);
// Toast.makeText(getApplicationContext(), "Image1=" + bal1,
// Toast.LENGTH_LONG).show();
} else if (flag == 2) {
bal2 = bal;
t7.setVisibility(View.GONE);
imgview2.setImageBitmap(photo);
// Toast.makeText(getApplicationContext(), "Image2=" + bal2,
// Toast.LENGTH_LONG).show();
} else if (flag == 3) {
bal3 = bal;
t6.setVisibility(View.GONE);
imgview3.setImageBitmap(photo);
// Toast.makeText(getApplicationContext(), "Image3=" + bal3,
// Toast.LENGTH_LONG).show();
} else if (flag == 4) {
bal4 = bal;
t8.setVisibility(View.GONE);
imgview4.setImageBitmap(photo);
// Toast.makeText(getApplicationContext(), "Image4=" + bal4,
// Toast.LENGTH_LONG).show();
}
Add ad = new Add();
ad.image_save(bal1, bal2, bal3, bal4);
// flag=0;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("message", largeImagePath);
outState.putString("Gallerymessage", picturePath);
}
onActivityResult() Method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_IMAGE_CAPTURE
&& resultCode == Activity.RESULT_OK) {
flagg = 0;
// Describe the columns you'd like to have returned. Selecting from
// the Thumbnails location gives you both the Thumbnail Image ID, as
// well as the original image ID
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select
// only
// mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
// At the moment, this is a bit of a hack, as I'm returning ALL
// images, and just taking the latest one. There is a better way to
// narrow this down I think with a WHERE clause which is currently
// the selection variable
myCursor = this.managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
// myCursor.close();
}
// Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
largeImagePath = "";
try {
myCursor.moveToFirst();
// This will actually give yo uthe file path location of the
// image.
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
// myCursor.close();
}
// These are the two URI's you'll be interested in. They give you a
// handle to the actual images
uriLargeImage = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
String.valueOf(imageId));
uriThumbnailImage = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the URI's
// to my own objects anyways...
// Toast.makeText(this, ""+largeImagePath,
// Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriLargeImage, Toast.LENGTH_LONG).show();
// Toast.makeText(this, ""+uriThumbnailImage,
// Toast.LENGTH_LONG).show();
if (largeImagePath != null) {
Toast.makeText(this, "LARGE YES" + largeImagePath,
Toast.LENGTH_LONG).show();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
// thumbnail = (BitmapFactory.decodeFile(picturePath));
thumbnail = BitmapFactory.decodeFile((largeImagePath), opts);
Bitmap bitmap = thumbnail;
System.gc();
try {
ExifInterface exif = new ExifInterface(largeImagePath);
orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation =" + orientation);
// exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90,
// 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
// m.postScale((float) bm.getWidth(), (float)
// bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(thumbnail, 0, 0,
thumbnail.getWidth(), thumbnail.getHeight(), m,
true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(thumbnail, 0, 0,
thumbnail.getWidth(), thumbnail.getHeight(), m,
true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(thumbnail, 0, 0,
thumbnail.getWidth(), thumbnail.getHeight(), m,
true);
}
} catch (Exception e) {
}
if (thumbnail != null) {
// Toast.makeText(this, "Try Without Saved Instance",
// Toast.LENGTH_LONG).show();
imageCam(bitmap);
}
}
if (uriLargeImage != null) {
// Toast.makeText(this, ""+uriLargeImage,
// Toast.LENGTH_LONG).show();
}
if (uriThumbnailImage != null) {
// Toast.makeText(this, ""+uriThumbnailImage,
// Toast.LENGTH_LONG).show();
}
}
if (requestCode == 1337 && resultCode == RESULT_OK) {
flagg = 0;
Bundle extras = data.getExtras();
// if (extras!=null){
if (extras.keySet().contains("data")) {
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 1;
// options.inPurgeable = true;
// options.inInputShareable = true;
thumbnail = (Bitmap) extras.get("data");
// image(thumbnail);
if (thumbnail != null) {
// Toast.makeText(this, "YES Thumbnail",
// Toast.LENGTH_LONG).show();
BitmapFactory.Options opt = new BitmapFactory.Options();
// options.inSampleSize = 1;
// options.inPurgeable = true;
// options.inInputShareable = true;
thumbnail = (Bitmap) extras.get("data");
imageCam(thumbnail);
}
} else {
Uri imageURI = getIntent().getData();
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
imageview.setImageURI(imageURI);
if (imageURI != null) {
// Toast.makeText(this, "YES Image Uri",
// Toast.LENGTH_LONG).show();
}
// Toast.makeText(CreateProfile.this, "Picture NOt taken",
// Toast.LENGTH_LONG).show();
}
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
flagg = 1;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
cursor1 = getContentResolver().query(selectedImage, filePathColumn,
null, null, null);
cursor1.moveToFirst();
int columnIndex = cursor1.getColumnIndex(filePathColumn[0]);
String picturePath = cursor1.getString(columnIndex);
// cursor.close();
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = OG;
// thumbnail = (BitmapFactory.decodeFile(picturePath));
thumbnail = BitmapFactory.decodeFile((picturePath), opts);
System.gc();
Bitmap bitmap = thumbnail;
try {
ExifInterface exif = new ExifInterface(picturePath);
orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation =" + orientation);
// exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
// m.postScale((float) bm.getWidth(), (float)
// bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(thumbnail, 0, 0,
thumbnail.getWidth(), thumbnail.getHeight(), m,
true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(thumbnail, 0, 0,
thumbnail.getWidth(), thumbnail.getHeight(), m,
true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(thumbnail, 0, 0,
thumbnail.getWidth(), thumbnail.getHeight(), m,
true);
}
} catch (Exception e) {
}
if (thumbnail != null) {
imageCam(bitmap);
} else {
Toast.makeText(this, "Please select a different picture",
Toast.LENGTH_LONG).show();
}
}
else {
// imgview.setBackgroundResource(R.drawable.bbtb);
}
}
}
I am making an android application that takes image from the camera and saves it in the gallery. What i want is to get path of the saved image. I have tried using intent.getData() but is not working..
I have tried using intent.getData() but is not working..
you Will get intent as NULL in Some Samsung Devices Like Samsung Galaxy S3 with Android OS Version 4.1.1.
i have face this Problems and Solve it by Below way you can try it out if it helps you.
While Calling intent for Image Capture :
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
mImageCaptureUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else {
new AlertDialog.Builder(BuildInukshk_4_Camera.this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState)
.setCancelable(true).create().show();
}
} else { // pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
Inside OnActivityResult Method :
case PICK_FROM_CAMERA:
Log.i("TAG", "Inside PICK_FROM_CAMERA");
// Final Code As Below
try {
Log.i("TAG", "inside Samsung Phones");
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select
// only
// mini's
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
// At the moment, this is a bit of a hack, as I'm returning ALL
// images, and just taking the latest one. There is a better way
// to
// narrow this down I think with a WHERE clause which is
// currently
// the selection variable
Cursor myCursor = this.managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
// myCursor.close();
}
// Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID
+ " DESC";
myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
// This will actually give yo uthe file path location of the
// image.
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
mImageCaptureUri_samsung = Uri.fromFile(new File(
largeImagePath));
mImageCaptureUri = null;
} finally {
// myCursor.close();
}
// These are the two URI's you'll be interested in. They give
// you a
// handle to the actual images
Uri uriLargeImage = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(thumbnailImageId));
// I've left out the remaining code, as all I do is assign the
// URI's
// to my own objects anyways...
} catch (Exception e) {
mImageCaptureUri_samsung = null;
Log.i("TAG",
"inside catch Samsung Phones exception " + e.toString());
}
try {
Log.i("TAG",
"URI Samsung:" + mImageCaptureUri_samsung.getPath());
} catch (Exception e) {
Log.i("TAG", "Excfeption inside Samsung URI :" + e.toString());
}
try {
Log.i("TAG", "URI Normal:" + mImageCaptureUri.getPath());
} catch (Exception e) {
Log.i("TAG", "Excfeption inside Normal URI :" + e.toString());
}
break;
After Running Below Code you Will get Two URIs mImageCaptureUri_samsung and mImageCaptureUri
you will get the mImageCaptureUri as your Path if you are running the App with Simple Devices and you will get your Cpatured Image path in mImageCaptureUri_samsung if you are running with Devices Like Samsung Galaxy S3.
Further you all can go ahead with your Code. it Works For me Very Fine With all the Devices i have tested on.
Also if Someone is having Problem with Above Code than they can reference the Below Great Link Solution of Samsung Galaxy S3
Hope it will Help.
try this one :
public class Camera extends Activity {
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TakePhoto();
}
public void TakePhoto()
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == CAMERA_REQUEST)
{
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
This is how I have done:
First create the image uri and with the intent ACTION_IMAGE_CAPTURE pass an extra MediaStore.EXTRA_OUTPUT with this value.
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
capturedImageURI = ImageUtils.takePicture(ReceiptFormActivity.this);
}
});
Then onActivityResult convert this uri path to String path and call the method which will fetch the bitmap from this string path and set it on your imageView.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONSTANTS.TAKE_PICTURE)
{
if (resultCode == RESULT_OK)
{
if(capturedImageURI != null)
{
Utils.imagePath = ImageUtils.getStringPathFromURI(ReceiptFormActivity.this, capturedImageURI);;
setThumbnail();
}
}
}
}
void setThumbnail()
{
try{
if(Utils.imagePath != null)
{
((TextView)findViewById(R.id.display_image)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File f = new File(Utils.imagePath);
if(f.exists())
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.fromFile(f);
intent.setDataAndType(imgUri, "image/*");
startActivityForResult(intent,2000);
}
}
});
File imgFilePath = new File(Utils.imagePath);
if(imgFilePath != null && imgFilePath.exists())
{
Bitmap bitmap = ImageUtils.decodeFile(imgFilePath, CONSTANTS.THUMBNAIL_HEIGHT, CONSTANTS.THUMBNAIL_WIDTH);
if(bitmap != null)
{
receipt_thumbnail.setImageBitmap(bitmap);
return;
}
}
}
}
catch (Exception e) {
receipt_thumbnail.setImageResource(R.drawable.some_img);
}
/*
* default img incase of not any exception and no bitmap either.
*/
receipt_thumbnail.setImageResource(R.drawable.some_img);
}
ImageUtils.java
public class ImageUtils {
public static Uri takePicture(Context context)
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Receipt_" + System.currentTimeMillis());
Uri mCapturedImageURI = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
((Activity) context).startActivityForResult(intentPicture,CONSTANTS.TAKE_PICTURE);
return mCapturedImageURI;
}
public static String getStringPathFromURI(Context context, Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
public static Bitmap decodeFile(File f, int thumbnailReqHeight, int thumbnailReqWidth)
{
Bitmap b = null;
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > thumbnailReqHeight || o.outWidth > thumbnailReqWidth)
{
scale = (int)Math.pow(2, (int) Math.round(Math.log(thumbnailReqHeight / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o);
fis.close();
} catch (IOException e) {
}
return b;
}
}
The code is very fine. Try giving permission of android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE in android manifest.