Cant start new activity from onActivityResult method in main activity - android

I have used following method to get image after calling photo gallery intent. I want to start another activity by passing the bitmap of that image and show that image in the second activity. But, nothing will happen after a photo is picked from photo gallery.
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
final String path;
if (requestCode == GALLERY_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
Uri imageFileUri = data.getData();
if (imageFileUri != null) {
try {
path = getPath(imageFileUri);
BitmapFactory.Options load_option = new BitmapFactory.Options();
load_option.inPurgeable = true;
load_option.inDensity = 0;
load_option.inTargetDensity = 0;
load_option.inDensity = 0;
load_option.inScaled = false;
bmp_main = BitmapFactory.decodeFile(path, load_option);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp_main.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intentPhoto = new Intent(MainActivity.this, SecondActivity.class);
intentPhoto.putExtra("image",byteArray);
startActivity(intentPhoto);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Can anybody tell what's the problem?
N.B.: 1.I have added the activity in the manifest
2. There is no logcat error or exception regarding this
3. I have done debugging, it goes upto startActivity line correctly, but after that nothing happen

Use below code...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri contentUri = data.getData();
startActivity(new Intent(this, ViewGallery_Photo.class)
.setData(contentUri));
}
So in onActivityResult there are 2 logic
1) if you are loading images from gallery then it will take you to other activity
2) if you are capturing image from camera then it will take you to other activity not the same activity which is calling by gallery ...

Call this out of your if condition:
Intent intentPhoto = new Intent(MainActivity.this, SecondActivity.class);
intentPhoto.putExtra("image",byteArray);
startActivity(intentPhoto);
Try this:
try {
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();
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "userImage" + ".png");
if (file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
fOut.flush();
fOut.close();
Log.v("Image saved", "in" + file);
} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
decodeFile(picturePath);
/*
* iv_display.setImageBitmap(mPhoto); Bitmap useThisBitmap =
* Bitmap.createScaledBitmap(mPhoto, mPhoto.getWidth(),
* mPhoto.getHeight(), true);
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
bytepicture = baos.toByteArray();
Intent newdata = new Intent(MainMenu.this, SecondActivity.class);
newdata.putExtra("picture", bytepicture);
startActivity(newdata);
} catch (Exception e) {
// TODO: handle exception
Log.v("TAG", "No Image Selected:");
}
For decode file :
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 3;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
mPhoto = BitmapFactory.decodeFile(filePath, o2);
myBitmap = ExifUtils.rotateBitmap(filePath, mPhoto);
// image.setImageBitmap(bitmap);
}

Related

how to capture an image using camera and save it server?

I want to capture an image using camera and store it in server. But I am getting null pointer exception after capturing the image. Completed mostly but this error is annoying. I am newbie to android i don't know why this error occurs. Need help thanks in advance
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA) {
if (data == null) {
Snackbar.make(parentView, R.string.string_unable_to_pick_image, Snackbar.LENGTH_INDEFINITE).show();
return;
}
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
decodeFile(finalFile.toString());}}
**getImageUri method **
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "aadhar", null);
return Uri.parse(path);//getting error here
}
getRealPathFromURI Method
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
decodeFile Method
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
imageView.setImageBitmap(bitmap);
}
Error
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:475)
at android.net.Uri$StringUri.<init>(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.androidbuts.ui.MainActivity.getImageUri(MainActivity.java:274)
at com.androidbuts.ui.MainActivity.onActivityResult(MainActivity.java:233)
at android.app.Activity.dispatchActivityResult(Activity.java:7139)
<!--First define permissions in Menifest-->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
// open camera as
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
// Then Retrive image As
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA && data != null) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File imageStorageDir = new File(Environment.getExternalStorageDirectory(),
getResources().getString(R.string.app_name));
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
imagePath = imageStorageDir + File.separator + "_NAME_YOU_WISH" + ".jpg";
fileImage = new File(imagePath); // FILE
try {
FileOutputStream out = new FileOutputStream(imagePath);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
if (fileImage != null) {
if (fileImage.isFile() && fileImage.exists()) {
// MyApplication.log(LOG_TAG, "onActivityResult() SHOWING IMAGE BY GLIDE, fileImage:-> " + fileImage.getAbsolutePath());
Glide.with(context)
.load(fileImage.getAbsoluteFile())
.asBitmap()
.placeholder(R.drawable.ic_broken_image)
.into(img_camera);
}
}
} catch (Exception e) {
//MyApplication.log(LOG_TAG, "onActivityResult() , Exception: " + e.getMessage());
}
}
}
// CALL THE FUNCTION TO SEND IMAGE TO SERVER
public void callSendCheckReport() {
MyApplication.showDialog(context, "Please Wait...");
HashMap<String, Object> map = new HashMap<>();
map.put("date", today);
map.put("salesman_id", MyApplication.get_session(MyApplication.SESSION_SALESMAN_ID));
if (actionStatus.equals("do_CHECK_IN")) { //// do_CHECK_IN, do_NO_CHANGE, do_CHECK_OUT
map.put("checkin", "yes");
map.put("in_time", checkTimeStamp);
if (fileImage != null)
map.put("in_image", new TypedFile("image*//*", fileImage));
}
RestClient.getWebServices().sendCheckReport(map,
new Callback<String>() {
#Override
public void success(String s, Response response) {
MyApplication.log(LOG_TAG, "Responce is----> " + s);
try {
JSONObject res = new JSONObject(s); // "status":"TRUE","message":"Shop Registered Successfully."}
String status = res.getString("status");
String message = res.getString("message");
MyApplication.stopLoading();
if (status.equals("TRUE")) {
if (fileImage.exists())
fileImage.delete();
}
showDialogBox(context, getResources().getString(R.string.app_name), message);
} catch (JSONException e) {
MyApplication.stopLoading();
// MyApplication.log(LOG_TAG + "RESPONSE JSONException ->" + e.getMessage());
}
}
#Override
public void failure(RetrofitError error) {
MyApplication.log(LOG_TAG + " RetrofitError ->" + error.getMessage());
MyApplication.stopLoading();
}
});
}

How to select an image from the gallery, re-size it and re-save it to a different gallery folder

I found some code on SO helping me bring up an image selector, save the image, re-size/decode it and display it in an ImageView, however I am wanting to know how to save this newly re-sized image into a different folder in the Gallery and then return it's new location (including the filename) as a String. Here is what I have so far:
Starting the image picker intent:
public void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
Getting the selected image:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = decodeUri(selectedImage);
imageIcon.setImageBitmap(yourSelectedImage);
imageText.setText("");
} catch (Exception e) {
Toast.makeText(this, "Image Selection Error", Toast.LENGTH_LONG).show();
}
}
}
}
Function to decode the image:
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 200;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
I am also unsure whether I have correctly implemented this decode function as changing the REQUIRED_SIZE int makes no difference when it's displayed in the ImageView.
I managed to solve this with the below method:
public void saveResizedImage(Bitmap image) {
File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "rapical" + File.separator);
String path = root.getPath();
OutputStream fOut = null;
File noOfImages[] = root.listFiles();
int fileCount = 0;
for (int i = 0; i < noOfImages.length; i++) {
fileCount++;
}
File foodImageFile = new File(path, "rapical" + fileCount + ".png");
try {
fOut = new FileOutputStream(foodImageFile);
image.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
String imagePath = path + "/rapical" + fileCount + ".png";
Log.w("ImagePath: ", imagePath);
} catch (Exception e) {
}
}

Picture path is null when selected an Image from the "Recent Images" folder

I'm tyring to upload an image for my application, here when I choose an Image from my Gallery it works fine, now If I select the same image from "Recent" folder the picture path is null and I'm unable to upload the image. Can you please help me resolving this issue.
Here's my code for your reference:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the views
image = (ImageView) findViewById(R.id.uploadImage);
uploadButton = (Button) findViewById(R.id.uploadButton);
takeImageButton = (Button) findViewById(R.id.takeImageButton);
selectImageButton = (Button) findViewById(R.id.selectImageButton);
selectImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImageFromGallery();
}
});
takeImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
/*
* Picasso.with(MainActivity.this) .load(link) .into(image);
*/
}
});
// when uploadButton is clicked
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// new ImageUploadTask().execute();
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT)
.show();
uploadTask();
}
});
}
protected void uploadTask() {
// TODO Auto-generated method stub
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String file = Base64.encodeToString(data, 0);
Log.i("base64 string", "base64 string: " + file);
new ImageUploadTask(file).execute();
}
/**
* Opens dialog picker, so the user can select image from the gallery. The
* result is returned in the method <code>onActivityResult()</code>
*/
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
}
/**
* Retrives the result returned from selecting image, by invoking the method
* <code>selectImageFromGallery()</code>
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
Log.i("selectedImage", "selectedImage: " + selectedImage.toString());
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
/*
* Cursor cursor = managedQuery(selectedImage, filePathColumn, null,
* null, null);
*/
cursor.moveToFirst();
// int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(columnIndex);
Log.i("picturePath", "picturePath: " + picturePath);
cursor.close();
decodeFile(picturePath);
}
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
image.setImageBitmap(bitmap);
}
Here's my log for your reference:
use this to display image in ImageView
Uri selectedImage = data.getData();
imgView.setImageUri(selectedImage);
OR use this..
Bitmap reducedSizeBitmap = getBitmap(selectedImage.getPath());
imgView.setImageBitmap(reducedSizeBitmap);
if you want to reduce the image size and also want to get bitmap
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Matrix matrix = new Matrix();
//set image rotation value to 90 degrees in matrix.
matrix.postRotate(90);
//supply the original width and height, if you don't want to change the height and width of bitmap.
b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
I ran into this same problem. While there are other ways to consume the URI, there is also a way to get the correct path.
See this issue:
retrieve absolute path when select image from gallery kitkat android
It's a bit outdated. Here's updated code.
Uri originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
/* now extract ID from Uri path using getLastPathSegment() and then split with ":"
then call get Uri to for Internal storage or External storage for media I have used getUri()
*/
String id = originalUri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri uri = getUri();
String filePath = "path";
Cursor imageCursor = getContentResolver().query(uri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
if(imageCursor.moveToFirst()) {
filePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
Make sure you have the read external storage permission. Also, note that the way you have it written worked pre-kitkat. Unfortunately, most examples still seem to use that method even though it's no longer guaranteed to work.
I hade same problem and found this solution from this github sample https://github.com/maayyaannkk/ImagePicker
This is the solution for your issue
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String imageEncoded = getRealPathFromURI(getActivity(), selectedImageUri);
Bitmap selectedImage = BitmapFactory.decodeFile(imageString);
image.setImageBitmap(selectedImage);
}
}
These method use for get image url
public String getRealPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = new File(getFilename(context));
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
private String getFilename(Context context) {
File mediaStorageDir = new File(context.getExternalFilesDir(""), "patient_data");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
}

unable to decode stream while selecting an image

While selecting an image from a gallery in my application it doesn't crash but instead its unable to decode the stream of the path. Taking the picture directly from the camera is working fine but from the gallery its not here is my code in my activity result .
//enter code here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK)
{
selectedImageUri = data.getData();
name = getPath(selectedImageUri);
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null)
{
try
{
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null)
{
decodeFile(filePath);
} else {
bitmap = null;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri)
{
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
public void decodeFile(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
//imgView.setImageBitmap(bitmap);
}
any help would be appreciated.
In later versions of Android (KitKat and above), the format of Uris returned from the gallery picker has changed, and it's not always possible to get a file path from a Uri without a lot of hassle, and sometimes it's not possible at all. So, it's better just to decode the bitmap using the Uri directly.
Change your decodeFile() function to accept a Uri and decode the image using BitmapFactory.decodeStream(), like this:
public void decodeFile(Uri fileUri)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o2);
//imgView.setImageBitmap(bitmap);
}
Then you can simplify your onActivityResult() code to this:
if(selectedImageUri != null)
{
try
{
decodeFile(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
If you have problems obtaining a valid Uri, see the accepted answer for this question for how to obtain a Uri inside OnActivityResult() with correct permissions on KitKat and above.
Well I choose another approach for this thing. You cannot diffrentiate between you chose a picture from gallery or from a Camera Intent.
Here is my code.
public class Chooser extends Activity {
ImageView imageView1;
private Uri outputFileUri;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
imageView1 = (ImageView) this.findViewById (R.id.imageView1);
Button frag1 = (Button) this.findViewById (R.id.frag1);
frag1.setOnClickListener (new OnClickListener () {
#Override
public void onClick (View v) {
choosePic (null);
}
});
}
public void choosePic (View view) {
// Determine Uri of camera image to save.
final File root = new File (Environment.getExternalStorageDirectory () + File.separator + "DCIM/Camera" + File.separator);
root.mkdirs ();
final String fname = "image_" + getRandomName () + ".jpeg";
final File sdImageMainDirectory = new File (root, fname);
outputFileUri = Uri.fromFile (sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent> ();
final Intent captureIntent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra (MediaStore.EXTRA_OUTPUT, Uri.fromFile (sdImageMainDirectory));
final PackageManager packageManager = getPackageManager ();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities (captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent (captureIntent);
intent.setComponent (new ComponentName (res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage (packageName);
intent.putExtra (MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add (intent);
}
// Filesystem.
final Intent galleryIntent = new Intent ();
galleryIntent.setType ("image/*");
galleryIntent.setAction (Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser (galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra (Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray (new Parcelable[] {}));
startActivityForResult (chooserIntent, 1);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
final boolean isCamera;
if (data == null) {
isCamera = true;
}
else {
final String action = data.getAction ();
if (action == null) {
isCamera = false;
}
else {
isCamera = action.equals (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
}
else {
selectedImageUri = data == null ? null : data.getData ();
}
imageView1.setImageURI (selectedImageUri);
}
}
}
public String getRandomName () {
Random r = new Random (); // just create one and keep it around
String alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";
final int N = 10;
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < N; i++) {
sb.append (alphabet.charAt (r.nextInt (alphabet.length ())));
}
return sb.toString ();
}

Taking a pic with tha camera but the image size is 0 KB

I have made a demo to make a pic with the cam, save the image, and then, in other activity show the last pic made it. This is OK with the emulator, but when I install my demo in a real phone, I can make the pic, but the file size saved is O KB.
//This is the method where I make the photo
private boolean makePhoto(){
try{
ImageCaptureCallback camDemo = null;
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
String filenameTimeStamp = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, String.format("%s.jpg", filenameTimeStamp));
values.put(ImageColumns.DESCRIPTION, "Imagen desde Android Emulator");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
Log.d("titulo: ", values.get(MediaColumns.TITLE).toString());
camDemo = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
this.camera.takePicture(this.mShutterCallback, this.mPictureCallback, camDemo);
Log.d("makePhoto", "Foto hecha");
return true;
}catch(Exception ex){
ex.printStackTrace();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, ex.toString(), duration);
toast.show();
}
return false;
}
//This is the object where the pic taken is saved
public class ImageCaptureCallback implements PictureCallback {
private OutputStream fileoutputStream;
public ImageCaptureCallback(OutputStream fileoutputStream){
this.fileoutputStream = fileoutputStream;
}
public void onPictureTaken(byte[] data, Camera camera){
try{
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap myImage = BitmapFactory.decodeByteArray(data, 0, data.length,options);
BufferedOutputStream bos = new BufferedOutputStream(this.fileoutputStream);
myImage.compress(CompressFormat.JPEG, 75, bos);
bos.flush();
bos.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
What happened?
I am sending you the code for taking picture and take the picture into your application.
First of all add the below intend:
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(i, CAMERA_PIC_REQUEST);
And then add the below startActivityForResule in your code
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case SELECT_PICTURE:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
// file path of selected image
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encode = Base64.encodeBytes(byteArray);
try {
byte[] decode = Base64.decode(encode);
Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
}
catch (IOException e) {
e.printStackTrace();
}
break;
case CAMERA_PIC_REQUEST:
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath);
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) 300) / width;
float scaleHeight = ((float) 300) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, width,
height, matrix, true);
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, baostream);
byte[] byteArrays = baostream.toByteArray();
encode = Base64.encodeBytes(byteArrays);
try {
byte[] decode = Base64.decode(encode);
Bitmap bitmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bitmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources