So I forked the cordova camera plugin because I wanted to modify it to return both a thumbnail and a regular size image when a picture is taken. I've never done android development before but this is what I have so far:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode / 16) - 1;
int destType = (requestCode % 16) - 1;
// if camera crop
if (requestCode == CROP_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bitmap thumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(croppedUri.toString()), 100, 100);
Uri thumbNailUri = getImageUri(this.cordova.getActivity().getApplicationContext(), thumbImage);
JSONArray imageArray = new JSONArray();
imageArray.put(croppedUri.toString());
imageArray.put(thumbNailUri.toString());
this.callbackContext
.success(imageArray);
croppedUri = null;
}// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = android.provider.MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
The problem is the application crashes when executing this code. It seems that the call BitmapFactory.decodeFile(croppedUri.toString()) returns a null value.
All the code I'm working with is here within the repo I linked above. All I'm trying to do is return the image paths to both the regular size image and the thumbnail.
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);
}
i am using a library for picking images from gallery and it is working , the problem is when i set the bitmap to the imageview it creates alot of duplicates in the gallery
here is the code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 11 && resultCode == RESULT_OK && data != null) {
ArrayList<Image> images = (ArrayList<Image>) ImagePicker.getImages(data);
for (int i = 0; i < images.size(); i++) {
String s = images.get(i).getPath();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
try {
bitmap = BitmapFactory.decodeFile(s, bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
imagesUrl2.add(bitmap);
uploadImages();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
the problem was with the glide loading from local uri ,it creates alot of instances in the gallery to get the image , so i passed the original uri of the images
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'm using the code below to pick an image file from device gallery:
First I call this piece of code:
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Picture"), RESULT_LOAD_IMAGE);
This is my onActivityResult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
photoPath = getPath(data.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(new File(photoPath));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf))) {
baos.write(buf, 0, n);
}
img.setImageBitmap(BitmapFactory.decodeFile(photoPath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
And this a helper method to retrieve image path:
private String getPath(Uri uri) {
String[] data = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
My problem is that the app is weird. In my 6.0 emulator, sometimes it works and sometimes No. In an other device (Android 5.1.1) an FileNotFound Exception is thrown at this line
fis = new FileInputStream(new File(photoPath));
All required permissions are fine.Do you guys have any idea what's going on here? Or do you have any better suggestion what to use to pick an image from gallery?
Try this you can directly set image from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try{
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Step #1: Delete the ByteArrayOutputStream, as you are not using it.
Step #2: Delete photoPath = getPath(data.getData()); and the getPath() method, as they are wrong.
Step #3: Use an image loading library to asynchronously populate your ImageView, passing it the Uri (data.getData()) of the image to load. Or, roll lots of your own image-loading code, including forking a background thread and using getContentResolver().openInputStream() to get an InputStream on the content identified by the Uri.
you can use like below code
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
//you are in fragment so use the below code hope its work
final Uri imageUri = data.getData();
final InputStream imageStream =getActivity().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
I am doing an android app, in which I have a functionality that, I need to open camera and take a picture. After taking picture onActivityResult is not called. my screen remains only in camera state.
My code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaFile = new File(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
Uri imageUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 1);
onActivityResult code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && !data.toString().equalsIgnoreCase("Intent { }"))
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
}
onActivityResult is probably called, but the statements inside your if statement and switch/case statements are not being executed, because they are never reached.
The code below includes two methods takePhoto and onActivityResult, is very short and works perfectly. Take a look at it, it probably will help you!
public void takePhoto(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
You can run your application in debug mode, after putting a breakpoint in onActivityResult method,
if it's stopping there after getting from the Camera then it's being called successfully.
and you could just change the if statement you're using making your code like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null && resultCode = RESULT_OK)
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
}
and note that it is more recommended to using final ints as the request code instead of rewriting them everytime they're needed
like :
private final int START_CAMERA_REQUEST_CODE = 1;
I think this may be help you
Follow Below Code step by step and compare with your code to avoid null exception
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
1 OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1)
onCaptureImageResult(data);
}
}
2
onCaptureImageResult
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
Uri tempUri = getImageUri(getApplicationContext(), thumbnail); // call getImageUri
File finalFile = new File(getRealPathFromURI(tempUri));
file_path = finalFile.getPath().toString(); // your file path
imgview.setImageBitmap(thumbnail);
// this code will get your capture image bitmap}
3 getImageUri
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, "Title", null); // your capture image URL code
return Uri.parse(path);
}
Using this code your screen will not remain more on camera state it will finish and image will be load as well you get image URL.
Bitmap mBitmap = BitmapFactory.decodeFile(imgPath);
pass Image path which you create from URI.
Probably, your activity is reloaded after camera is finished, but your code is not prepared to such situation.
See Android startCamera gives me null Intent and ... does it destroy my global variable?.
I think onActivity is called but it doesn't go into the if condition
Check only for null in if condition:
if (data != null )
switch (requestCode) {
case 1:
Log.i("StartUpActivity", "Photo Captured");
Uri uri = data.getData();
String imgPath = getRealPathFromURI(uri);
bitmap = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),
bitmap, null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
img1.setImageBitmap(bitmap);
}
From where you are calling startActivityForResult(intent, 1),
and where you Overriding onActivityResult() ?
I mean if you call startActivityForResult() from Frgment then you should override onActivityResult() in fragment it self, same applies to Activity also.