Context:
I'm creating a simple application where the user clicks a button, they choose a picture from their phone and the image will be displayed in the application. I accomplish this by launching an intent for the user to choose an image.
Problem:
When the user chooses the picture, if it's a .jpg file, it's not displayed. However, if it's a .png file, it works as expected.
Note:
I've verified that the Bitmap result is not null and there are no errors in logcat or any messages from the decodefile method
Any help would be greatly appreciated
The code:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Toast.makeText(getApplicationContext(), "path is " + selectedImagePath, Toast.LENGTH_LONG).show();
ImageView image = (ImageView)findViewById(R.id.selectedImage);
if (image == null)
Toast.makeText(getApplicationContext(), "No image to update", Toast.LENGTH_SHORT).show();
Bitmap result = BitmapFactory.decodeFile(selectedImagePath);
if (result == null)
Toast.makeText(getApplicationContext(), "Couldn't upload image because it's null", Toast.LENGTH_LONG).show();
image.setImageBitmap(result);
}
}
Could you try with an InputStream. Like this:
if (requestCode == SELECT_PICTURE){
Uri selectedImageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(selectedImageUri );
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
ImageView image = (ImageView)findViewById(R.id.selectedImage);
image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
It's weird, but my code is now working, but I didn't change anything.
Related
I've been developed app to take a picture to be saved in gallery. I've searched online and the easiest way that I could practice was to use data.getExtras().get("data") . So below are the code to take picture from camera. Note that I'm using fragment in this class.
img22a1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_01);
}
});
Get the captured image and convert it to string
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_01) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
byte[] byte_arr = output.toByteArray();
((SiteProgress) getActivity().getApplication()).seti22a1(Base64.encodeToString(byte_arr, Base64.DEFAULT));
BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);
img22a1.setBackgroundDrawable(ob);
} else if (resultCode == Activity.RESULT_CANCELED) {
}
}
}
I save the string into global variable so another activity can access it.
In another activity, I have a button to save the image into folder/gallery by accessing the image string.
for(int i=0;i<=namefile.length;i++){
Bitmap[] bitmap = new Bitmap[namefile.length];
FileOutputStream outputStream = new FileOutputStream(String.valueOf(namefile[i]));
bitmap[i] = BitmapFactory.decodeByteArray(decodedString[i],0,decodedString[i].length);
bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), namefile[i].getAbsolutePath(), namefile[i].getName(), namefile[i].getName());
}
It worked to save the image into folder/gallery....But the quality of image was very low...I could barely see text in the image.
They said data.getExtras().get("data") supposed to return thumbnail and not the actual image. What I want here is to get the full image and not the thumbnail one.
Any answer will be very appreciated.
From: Android - How to get the image using Intent data
if(data != null)
{
Uri selectedImageUri = data.getData();
filestring = selectedImageUri.getPath();
Bitmap thumbnail = BitmapFactory.decodeFile(filestring, options2);
System.out.println(String.format("Bitmap(CAMERA_IMAGES_REQUEST): %s", thumbnail));
System.out.println(String.format("cap_image(CAMERA_IMAGES_REQUEST): %s", cap_image));
cap_image.setImageBitmap(thumbnail);
}
Android: How to get an image from gallery if image size less than 1MB ??
+++My Code:
Bitmap bitmap;
private void onBrowse() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 111);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 111 && resultCode == RESULT_OK && data != null){
Uri path = data.getData();
File file = new File(path.getPath());
long size = file.length();
Log.i("size=", size + "");
if(size > 1048576){ // 1MB
Toast.makeText(this, "Image must less than 1MB.", Toast.LENGTH_SHORT).show();
return;
}
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
ivImage.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
+++Output: I/size=: 0
I selected image 3.2MB, why did output 0?
I want to show an image in ivImage if file size of selected image less than 1MB.
Please help!!!
I understand this question has been asked before and I have researched possible solutions with no luck so here it goes. I am trying to save an cropped image into a sqlite database. I am using the Android-Image-Cropper cropper library as follows in my onActivityResult() method:
Everything works except the part where I am trying to save the image as a bitmap. I keep getting null. I can however populate my ImageView with the line
ivTroopPhoto.setImageURI(result.getUri());
If anyone has used this API an can help me out with this issue.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == PIC_FROM_CAMERA) || (requestCode == PIC_FROM_GALLERY)) {
if (resultCode == RESULT_OK) {
Uri picUri = data.getData();
CropImage.activity(picUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setFixAspectRatio(true)
.setAspectRatio(1, 1)
.start(this);
}
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
ibCameraIcon.setVisibility(View.GONE);
ivTroopPhoto.setVisibility(View.VISIBLE);
ivTroopPhoto.setImageURI(result.getUri());
tvTroopPhoto.setText(R.string.change_photo);
Log.d("dozer74", "==============================> Image Uri: " + result.getUri().getPath());
//Uri imageUir = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), result.getUri());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.d("dozer74", "==========> Encoded Base64 Image: " + encoded);
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, String.format("Cropping failed: %s", result.getError()), Toast.LENGTH_LONG).show();
}
}
}
I was able to work it out. I used the api's imageview and was able to get the image as a bitmap.
I am using camera in my app.I need to take picture and should display it in imageview. I am using the following code to take picture from the camera and display it.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, 0);
imageView.setImageURI(capturedImageUri);
This works only for two or sometimes three images,then the imageview doesn't show the image but the image is correctly stored in SD card.
Alternatively i have also used
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
Imageview.setImageBitmap(bitmap);
But i am facing the same problem. can any one help me please.
capturedImageUri will return path to captured Image not the actual Image..
Also, Important Note-- If you dont need a full sized image use-
// cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); Comment this line
Bitmap image = (Bitmap) data.getExtras().get("data");
To get the full sized Bitmap Use following code-
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try
{
// place where to store camera taken picture
tempPhoto = createTemporaryFile("picture", ".png");
tempPhoto.delete();
}
catch(Exception e)
{
return ;
}
mImageUri = Uri.fromFile(tempPhoto);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(cameraIntent, 1);
private File createTemporaryFile(String part, String ext) throws Exception
{
// File to store image temperarily.
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ContentResolver cr = getApplicationContext().getContentResolver();
try {
cr.notifyChange(mImageUri, null);
File imageFile = new File(tempPhoto.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
Bitmap photo=null;
if (resultCode == 1) {
try {
photo = android.provider.MediaStore.Images.Media.getBitmap(cr, Uri.fromFile(tempPhoto));
imageView.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Have you tried putting your setImageUri logic in the activity callback onActivityResult
I think you are trying to supply the image to the imageview before any content is saved to that uri. You need to hook into the callback that gets fired when the camera actually take the picture (i.e. the camera activity finishes and reports its result)
This answer has a full write up
https://stackoverflow.com/a/5991757/418505
possibly something like
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
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);