I'm a noob to android and i want to set an ImageButton image with a file form the SDcard. However, getBitmap isn't creating a working bitmap. When i set the ImageButton with the bitmap that has just been created, the dimensions of the imageButton change but the image doesn't appear. This is really frustrating and Any help resolving this is greatly appreciated.
MYCODE
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
// If the file selection was successful
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
final Uri uri = data.getData();
try {
// Create a file instance from the URI
final File file = FileUtils.getFile(uri);
Toast.makeText(Profile_Barber.this,"File Selected: "+file.getAbsolutePath(), Toast.LENGTH_LONG).show();
Log.e("URI", uri.toString());//Returns: content://media/external/images/media/1834
Bitmap bmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
if(bmp==null){
Log.e("BMP NULL", "This that bullshit!");
}else{
Log.e("BMP NOT NULL", bmp.toString()); //Returns: BMP NOT NULL android.graphics.Bitmap#4152b5a0
profilepic.setImageBitmap(bmp);
}
} catch (Exception e) {
Log.e("FileSelectorTestActivity", "File select error", e);
e.printStackTrace();
}
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
How about using this to decode image?
Uri contentURI = Uri.parse(data.getDataString());
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(contentURI);
Bitmap pic = BitmapFactory.decodeStream(in,null,null);
Related
I am trying to fetch location of captured picture from camera. When I tried Exif interface but still return null value from photos.Please somebody help...
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
img1 = cursor.getString(cursor.getColumnIndex(filePath[0]));
ExifInterface exif = null;
try {
exif = new ExifInterface(img1);
} catch (IOException e) {
e.printStackTrace();
}
String lat = ExifInterface.TAG_GPS_LATITUDE;
String lat_data = exif.getAttribute(lat);
Log.e("MYDATA", lat_data);
cursor.close();
Toast.makeText(this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
Use Content resolver to build ExifInterface with inputStream
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode != Activity.RESULT_OK) {
return;
}
final Uri originalUri = intent.getData();
try {
final InputStream inputStream = getContext().getContentResolver().openInputStream(originalUri);
final android.support.media.ExifInterface exif = new android.support.media.ExifInterface(inputStream);
final double[] latLong = exif.getLatLong();
Log.v(LOG_TAG, "Image selected at position: " + latLong[0] + " : " + latLong[1]);
} catch (IOException e) {
Log.w(LOG_TAG, "Error when getting location from image", e);
}
}
Support lib import
compile 'com.android.support:exifinterface:x.x.x'
In my application ,on clicking Image View i want to start Camera which will capture image and display it in another image view.My code is given below:
//On clicking Camera
iv_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Log.e("Result Code", String.valueOf(resultCode));
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = data.getData();
Log.e("ImageUri", String.valueOf(selectedImageUri));
String realPath = getRealPathFromURI(selectedImageUri);
Log.e("Real Path", realPath);
imgProfilePic.setImageBitmap(photo);
}
}
}
//Get real path form Uri
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(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();
}
}
My problem is that ,on some mobiles it is working fine but on some it is not. For example: If i am testing my application using on my phone Yu Yureka having Lollipop ,it is giving me data as null.Also when the orientation changes,application is crashing .Please help me to fix the issue.
In your Manifest file use these permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Implement from this Simple Code Example this is my working example code
public void CameraClick(View v) {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// creating Dir to save clicked Photo
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Intent");
myDir.mkdirs();
// save clicked pic to given dir with given name
File file = new File(Environment.getExternalStorageDirectory(),
"/cam_Intent/MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Bitmap bitmap = null;
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (requestCode == TAKE_PIC && resultCode==RESULT_OK) {
String uri = outPutfileUri.toString();
Log.e("uri-:", uri);
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
//Bitmap myBitmap = BitmapFactory.decodeFile(uri);
// mImageView.setImageURI(Uri.parse(uri)); OR drawable make image strechable so try bleow also
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outPutfileUri);
Drawable d = new BitmapDrawable(getResources(), bitmap);
mImageView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
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();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}
I'm trying to save an image loaded from the gallery to the phone memory(local path). Can anyone guide me into this?
This is how I get the image from the gallery.
ImageView profilePicture;
private Uri imageUri;
String picturePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
profilePicture = (ImageView) findViewById(R.id.profile_picture);
profilePicture.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN: {
break;
}
case MotionEvent.ACTION_UP:{
uploadImage();
break;
}
}
return true;
}
});
}
uploadImage()
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
profilePicture.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
case 1:
if (resultCode == Activity.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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
profilePicture.setBackgroundColor(Color.TRANSPARENT);
profilePicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
*Note: Case 0 is for image capturing using phones camera.
I can display it on my imageview but I need to store this in the phone's memory so everytime I will open the app, I will be able to load the previous uploaded image to the image view. Then if the user wants to upload again. The file previously saved will just be overwritten. I don't want to result to storing images as blob using sqlite since I will be uploading just one image for my whole app. I want to store it in a local file path like myappname/images/image.png. Any ideas? Thanks!
You can store an image in the application cache directory such as:
try {
String destFolder = getCacheDir().getAbsolutePath()+ "/images/";
if (!new File(destFolder).exists()) {
new File(destFolder).mkdirs();
}
FileOutputStream out = new FileOutputStream(destFolder + "profile.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
And read back the file into the Bitamp:
String fname = "profile.png";
Bitmap profile = BitmapFactory.decodeFile(getCacheDir().getAbsolutePath()+ "/images/" + fname);
I've read the example to do this:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri imageUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
}
}
But i get java.io.FileNotFoundException: No content provider: /sdcard/Hello/1310610722879.jpg
My code is here:
Uri uri1 = Uri.parse(Config.getPhotoPath(this));
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri1);
attachButton.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Any ideas how to make it work?
Ok I messed around, u have to do this:
Uri uri1 = Uri.parse("file://" + Config.getPhotoPath(this));
Ok I messed around, u have to do this:
Uri uri1 = Uri.parse("file://" + Config.getPhotoPath(this));
Or you can do
File file = new file(Config.getPhotoPath(this));
Uri uri1 = Uri.fromFile(file);