UPDATE!!
So Lokesh put me on the right path, and showed me that the problem was the size of the file being too large to show in the imageview. I was able to fix the imageview preview problem with the following code under my onActivityResult:
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/td01.png");
int nh = (int) ( picture.getHeight() * (512.0 / picture.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(picture, 512, nh, true);
Log.v("Path", Environment.getExternalStorageDirectory().getPath()+"/td01.png");
pic1.setImageBitmap(scaled);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
Thanks Lokesh!
----------------- ORIGINAL ISSUE BELOW THIS LINE -------------------
So I'm trying to both save an image to the SD card for use later, AND display the saved image in an imageview which also serves as the button which takes the photo. Here's the code:
pic1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent camera_intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File image1 = new File(Environment.getExternalStorageDirectory(),"td01.png");
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image1));
startActivityForResult(camera_intent, CAMERA_PIC_REQUEST1);
}
});
followed by:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case 1:
if(resultCode==RESULT_OK){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
pic1.setImageBitmap(thumbnail);
}
}
Now, if I remove the following code from the onclick, it shows the thumbnail as I expect it to:
File image1 = new File(Environment.getExternalStorageDirectory(),"td01.png");
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image1));
...but without that code, it doesn't save the file to my sd card.
The problem is, if I don't remove that code, it saves the image to my SD Card but immediately crashes before returning to the activity after tapping SAVE in the camera activity, unless I remove the following code from my onActivityResult:
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
pic1.setImageBitmap(thumbnail);
I've also tried many variations of the following code in my onActivityResult, hoping to display it from the actual file in a different way, but it never works and only shows a blank imageview, but at least in that case the crash doesn't occur, because I removed the get extras get data code:
Bitmap photo1 = BitmapFactory.decodeFile("/sdcard/td01.png");
pic1.setImageBitmap(photo1);
I've been struggling with this for days and am at a loss here. Hope someone can show me what stupid thing I'm doing wrong and explain why this isn't working.
Thanks!
Try this:
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
Log.v("Path", Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
mImageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
do NOT access the SD card directly, try accessing it trough Environment Like this
String imageDir = Environment.getExternalStorageDirectory()+"/apple.jpg";
and then you can call BitmapFactory:
Bitmap myBitmap = BitmapFactory.decodeFile(imageDir);
Related
In an app I am allowing user to pick image from gallery or he can choose from camera. Though I can manage the image and show it in the activity in the first time, after closing the app and restarting it, the image is gone and the space is blank.There was an explanation given to me to save the image data in sharedPreferences but I am new in android and don't pretty much understand. I looked for sharedPreferences but don't know how to make it work.
So if anybody help kindly with some explanation and code, it would help me a lot.
Thanks.
Here is what I tried to do.
private void openCamera(){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,getPhotoFileUri(photoFileName)); // set the image file name
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(getPackageManager()) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, TAKE_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// final android.widget.LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageview.getLayoutParams();
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
imageview.setImageURI(imageUri);
//selectedImagePath = getPath(imageUri);
//ystem.out.println("Image Path : " + selectedImagePath);
}
else if (requestCode == TAKE_IMAGE && resultCode == Activity.RESULT_OK) {
Uri takenPhotoUri = getPhotoFileUri(photoFileName);
// by this point we have the camera photo on disk
Bitmap rawTakenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
// RESIZE BITMAP, see section below
// See BitmapScaler.java: https://gist.github.com/nesquena/3885707fd3773c09f1bb
// Get height or width of screen at runtime
int screenWidth = DeviceDimensionsHelper.getDisplayWidth(this);
// Resize a Bitmap maintaining aspect ratio based on screen width
Bitmap resizedBitmap = BitmapScaler.scaleToFitWidth(rawTakenImage,screenWidth);
// Load the taken image into a preview
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// Compress the image further
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// Create a new file for the resized bitmap (`getPhotoFileUri` defined above)
Uri resizedUri = getPhotoFileUri(photoFileName + "_resized");
File resizedFile = new File(resizedUri.getPath());
// Write the bytes of the bitmap to file
try{
resizedFile.createNewFile();
FileOutputStream fos = new FileOutputStream(resizedFile);
fos.write(bytes.toByteArray());
fos.close();
}catch (IOException e){
System.out.println("Error occured");
}
imageview.setImageBitmap(rawTakenImage);
}
}
public Uri getPhotoFileUri(String fileName) {
// Only continue if the SD Card is mounted
if (isExternalStorageAvailable()) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName));
}
return null;
}
// Returns true if external storage for photos is available
private boolean isExternalStorageAvailable() {
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
You can use below ways to store image.
1. Database with Base64
You can convert image into base64 string and store in database.
So when you open application you can retrieve base64 String from database and display image in ImageView.
2. Store Image Path in Database
You can store image path in database, when you open application, just retrieve image path and display image in ImageView.
But if you delete image from memory, you will not get image from iamge path.
3. Store Image in Server.
If you store image in server, you can retrieve image path and download image using AsyncTask or sime 3rd party liberary. And display image in ImageView.
(Liberaries : Picaso, LazyLoading etc.)
I've found a lot of answers for questions like mine but they doesn't make sense for me. Let me explain.
I have a ImageButton that let the user take a picture and display it on interface. When i try to get image URI, it returns null:
Uri uri = data.getData();
I've made some searches on internet and found solutions like:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
try {
if (resultCode == Activity.RESULT_OK) {
updateProfilePicure = Boolean.TRUE;
switch(requestCode){
case 0:
Bundle extras = data.getExtras();
Object xx = data.getData();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Uri tempUri = getImageUri(imageBitmap);
imageView.setImageBitmap(imageBitmap);
break;
default: break;
}
}
} catch(Exception e){
e.printStackTrace();
}
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(
ApplicationContext.getInstance().getContext().getContentResolver(), inImage,
"Title", null);
return Uri.parse(path);
}
For me, it doesn't make sense because when the call goes to method onActivityResult(), the picture is already saved on DCIM folder and don't have any reason to save it again. So why should i use it?
Is possible to find another way to retrieve the URI from captured image?
Thank's in advance.
the picture is already saved on DCIM folder and don't have any reason to save it again.
Not necessarily. Quoting the documentation for ACTION_IMAGE_CAPTURE:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field.
(the "extra field" here is an extra keyed as data)
The code snippet that you pasted is retrieving the data extra, and so the image is not stored anywhere.
Is possible to find another way to retrieve the URI from captured image?
You already have the code for this, in your first code snippet -- if you are specifying the Uri as EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE request, you will get a Uri back to the image that was taken in the Intent handed to onActivityResult().
I have an ImageView after getting id from xml.as
on ImageView we set clicklistener which open gallery and camera opetion you can set image from camera as well gallery
ain #2
profileimage = (ImageView) findViewById(R.id.profileimage);
profileimage.setBackgroundResource(R.drawable.no_img);
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
// TODO
return;
}
Log.e("request code", "1:" + requestCode);
switch (requestCode) {
case CAMERA_SELECT:
Log.e("in camera select", "1");
// Get the camera data
cameracalling(intent);
break;
case Gallery_Select:
ongallerycalling(intent,resultCode);
}
}
private void cameracalling(Intent intent){
Bitmap photo = (Bitmap) intent.getExtras().get("data");
profileimage.setImageBitmap(photo);
}
profileimage.buildDrawingCache();
Bitmap bmap = profileimage.getDrawingCache();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
bitmapString=Base64.encodeBytes(ba);
Drawable draw = LoadImageFromWebOperations("" + objUserInformationSitesList.getProfileImage());
profileimage.setBackgroundDrawable(draw);
We are sending bitmap string to server image upload on server properly but when we open next time this screen that webservice call on which we upload image which will give all data (actually this user profile screen) .when we set server image then default image also set on background
objUserInformationSitesList this object which contains all information after parsing the web service. behind profile image ,default image also looking which set by me on number #1
if I unable to explain properly then please tell me.
use in onclicklistener
profileimage.setBackgroundResource(0);
You should replace below line:
profileimage.setBackgroundResource(R.drawable.no_img);
with this line:
profileimage.setImageResource(R.drawable.no_img);
You set the image as the background of drawable and later you set bitmap as image source. So imageview background doesn't change. You should set image as image resource.
I am using android inbuilt camera to take picture and then attaching the same picture to email, when i am testing this functionality in 1.6 device, i am able name the picture that to be taken by in built camera, but in 2.1, the picture is having a name i.e given by device,
How to give user defined name in 2.1 inbuilt camera images..
to avoid that problem i am saving the image manually but when i try to get the image back through intent as bitmap and then saving it to sd card using compress method
this methods handles result from inbuilt camera
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
File file = new File(Environment.getExternalStorageDirectory()
+ "/test.png");
switch (requestCode)
{
case PHOTO_ACTION:
if (resultCode == RESULT_CANCELED)
{
addPhoto = false;
Toast.makeText(this, "Canceled ", Toast.LENGTH_LONG).show();
break;
} else if (resultCode == RESULT_OK)
{
Bundle b = data.getExtras();
Bitmap bm = (Bitmap) b.get("data");
FileOutputStream out;
try
{
out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
scanPhoto(file.toString());
out = null;
addPhoto = true;
} catch (Exception e)
{
e.printStackTrace();
addPhoto = false;
}
but when i am storing like this i am getting two images. one with system given name and other with name given by me. but the image one which has user defined is having less resolution so i question is how to save the bitmap with more resolution with out compressing it ..
please help.... me
If you just want to save the bitmap without losing quality try using CompressFormat.PNG instead of JPEG, I've seen people having that problem before. Try changing:
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
with:
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
and see it it helps.
Apart from Rick answer above, make sure your are providing a URI to camera intent where it can save the full image, else it will return thumb image in data parameter of intent.
So it will be like:
Intent photoPickerIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imgFile = new File("Cache directory","img.png"); //== where you want full size image
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(imgFile));
startActivityForResult(photoPickerIntent, PickPhoto);
This was the error that I was doing.
here is the problem: i have searched for an answer for this and so far i made it work for the custom camera app that comes with htc phones.
i have the folowing
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_FROM_CAMERA && resultCode == RESULT_OK) {
InputStream is=null;
File file=mInterface.getTempFile();
try {
is=new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if(is==null){
try {
u = data.getData();
is=getContentResolver().openInputStream(u);
mInterface.saveStringPreferences(GlobalInterface.URI_SAVENAME, u.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//Now "is" stream contains the required photo, you can process it
setImage(is);
}
//and this is the code to the function that calls the intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(mInterface.getTempFile()));
startActivityForResult(intent, REQUEST_FROM_CAMERA);
the remaining functions getTempFile() is to create a temp file on /sdcard/blabla.tmp
and a function to set the captured image in an image view.
so the problem is that i tested this code on the custom camera on a lg phone and it crashes. the question is: is there a way to get an uri for the image location (i dont need a specific save location it could be the default set from the camera) and there were also some issues i came across which i dont need to solve like getting a smaller resolution image. i just need one image and to be able to set it in an imageView and the method to work for every camera app that is there, custom or native regardless.
is this possible or i need to create a new camera class for this? in my opinion the camera apps that come with the phone are more adjusted to the phone model so i would prefer using them against building a custom one.
tnx.
Try this:
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Source