Saving cropped image into SQLite database - android

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.

Related

Code crashes when displaying image in imageview

Thia code crashes when i took a photo from camera. but when i pick a photo from gallery it works fine. please guide me. I debug this code. the value of data is getting null when i took a picture from camera
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK || requestCode == 200||requestCode==CAMERA_REQUEST) {
Glide.with(this).load(data.getData()).into(mDishUploadImg);
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mainActivity.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
base64img = Base64.encodeToString(b, Base64.NO_WRAP);
}
}
Try Adding data!=null && data.getData() != null into your if Statement and also instead of using || use &&.

Capture image from camera return low quality image

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);
}

Portrait Camera Images when Uploaded via Library rotates in ImageView Android

In my Android App, I have an option where a user can take his photograph or upload an image from his Gallery at the time of registration. This image, once successfully taken by camera or selected from Gallery, is shown in an ImageView. Below is the onClick of ImageView code that starts this process.
This is from Activity Layout.
<ImageView
android:id="#+id/imgUserImage"
android:layout_width="150dp"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:onClick="changePicture"
app:srcCompat="#drawable/profile_image_not_provided"
android:layout_below="#+id/textView2"
android:layout_alignParentEnd="true"
android:layout_marginTop="10dp" />
This is from Activity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);
int exif_orn_a;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
imgProfilePicture.setImageURI(selectedImage);
imgProfilePicture.setImageBitmap(mphoto);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Bitmap lphoto = null;
Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
}
if (cur != null) cur.close();
try {
lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imgProfilePicture.setImageURI(selectedImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have managed to get the Orientations properly. Now the problem is, how should I rotate the image before imgProfilePicture.setImageURI(selectedImage);.
I managed to find the solution. Please feel free to post a better solution, if you think this can be improvised.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);
int exif_orn_a;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
imgProfilePicture.setImageURI(selectedImage);
imgProfilePicture.setImageBitmap(mphoto);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
//Starting from here, I am checking the Orientation and storing the result in orientation variable.
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Bitmap lphoto = null;
Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
}
if (cur != null) cur.close();
//This is the end of Orientation Check.
try {
lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imgProfilePicture.setImageURI(selectedImage);
//Based on the Orientation Check result, I rotate the ImageView Image to make it straight.
if (orientation == 270) {
imgProfilePicture.setRotation(-90);
} else if (orientation == 0) {
imgProfilePicture.setRotation(0);
}
//This is the end of Image Rotation based on the Orientation Check Result.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Returning thumbnail file path from camera

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.

Android - Using BitmapFactory.decodefile with jpeg files does not work

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.

Categories

Resources