compressing selected image file/taken from camera - java

trying to let users add profile pictures, but I want to compress the image file before sending it to the server.
How can i compress the:
File imageFile = new File(resultUri.getPath());
Tried and searched but couldn't get to work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
btnConfirm.setVisibility(View.VISIBLE);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File imageFile = new File(resultUri.getPath());
progressDialog.show();
AndroidNetworking.upload("https://myweb.com/uploadImg.php")
.addMultipartFile("image", imageFile)
Would love to get some advice, Thanks in advance.

Check this
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}

Related

Resgistering photos issues in android programming

I am implementing an android app using camera to take pictures then registering it in External_storage\Android\data\com.abc.projectname.bf . But after openning the camera , even if i don't capture , an image file is registered in the directory . How can i solve that , here is the code :
public void onCapturePhoto(String fileName){
//Intent to take photos
File storageDirectory = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
Log.d("#picName",fileName);
File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
currentPhotoPath = imageFile.getAbsolutePath();
Uri imageUri= FileProvider.getUriForFile(requireActivity(),"com.ticanalyse.mheath.bf",imageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,1);
Log.d("#image_length is ",String.valueOf(imageFile.length()));
} catch (IOException e) {
e.printStackTrace();
}
}
//
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
// imageView.setImageBitmap(imageBitmap);
// File f = new File(currentPhotoPath);
//// Uri contentUri = Uri.fromFile(f);
// Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
// //Convert bitmap to byteArray
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// byte[] byteArray = byteArrayOutputStream .toByteArray();
// //Then convert to base64
// encodedImage= Base64.encodeToString(byteArray, Base64.DEFAULT);
// Log.d("#base64",encodedImage);
// setPic();
}
}
First of all, have the imageFile object from this line:
File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
...declared as a global in the Activity like this...
public class XYZActivity extends AppCompatActivity {
private File imageFile;
//onCreate(), onCapturePhoto(), etc methods
}
Then in onCapturePhoto():
imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
Now in the onActivityResult(), if you ensure that no image was taken/clicked, you could try deleting the temporary file like this:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Your stuff...
}
else {
//No photo was taken or clicked...
//Thus, deleting the temporary file...
if (file.exists()) {
if (file.delete()) {
Log.i("Process", "Deletion DONE!");
}
}
}
}
If I interpreted any part of problem in a undesirable way, please let me know.

android take image from phone album and store it in sqlite database

i'm making an app where the user can choose images from the phone's album and store it into a table in sqlite database, i have seen many posts here about this issue but couldn't understand the solutions (neither did they work for me), in my activity i have an imageview which when clicked will open the album and allow the user to choose an image and also i have a button which when clicked will store the image in sqlite database, i'm just able to choose the image but after that i'm stuck, i got to this method in my code:
public void getImage(View view) throws IOException {
ImageView v=(ImageView)view;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent,1);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContext().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
now what should i do after this to store the image in the db?
If you are sure about the images will not be removed from internal storage, you can save the image path. If want to save the image data, you can do the following.
for selecting image
private void selectImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQ);
}
In onActivityResult, from Intent data ...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQ && resultCode == Activity.RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), path);
Bitmap.createScaledBitmap(bitmap, 150, 150, true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
get byte[] from bitmap
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if(bitmap == null) return null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
then save the byte[] as blob in sqlite
for getting the images as bitmap
public static Bitmap getBitmapFromByteArray(byte[] blob){
if(blob == null) return null;
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
return bitmap;
}

Uploading and retrieving image android studio Parse sever

I'm trying to pick multiple images from users gallery and upload (parse server) this images to parse object then retrieve it and set it in an image view
and also i need to pick one image from gallery and save to the users profile
what i have already tried:
//Before OnCreate
String da = "13412412412412414124ASDASDASDASDAD";
////After OnCreate
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final Uri imageUri = data.getData();
final InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
da=encodedImage;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private String encodeImage(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
private void ChooseImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
}
private void CreateThing() {
ParseObject thing = new ParseObject("Things");
thing.put("Image",da);
thing.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e==null)
Toast.makeText(class.this, "Done", Toast.LENGTH_SHORT).show();
else
Toast.makeText(class.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

Capture Image and display as Base64 String

I'm an absolute newbie and want to build an app with Android that accesses the camera, takes a picture, cuts it and displays the result as Base64 code only.
I already did some research and built the following code, but the Base64 output doesn't work.
Thanks for your help!
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap); //displaying bitmap works
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
textView.setText(byteArray); //doesnt work
}
}
You have your textView.setText(byteArray); after your 'return' statement. That statement will never be executed. I think you should do this:
String strReturn = Base64.encodeToString(byteArray, Base64.DEFAULT);
textView.setText(strReturn);
return strReturn;
Oh, yes, you are not calling the method to base64 encode the bitmap to string... you would do it this way:
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
//HERE IS WHAT YOU NEED TO ADD
textView.setText(bitmapToBase64(bitmap));
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
//THIS CHANGED A BIT
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encodedImage;
}
Thanks for the tip. I'm afraid it didn't help. I guess that bitmap is not passed from the first method (?) to the second. Could that be? And what is the best way to fix that?
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
textView.setText(encodedImage);
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

Change an image that is store in parse through android

I am trying to update an image that is saved in parse through the android app, I am able o retrieve it and load it to the app but I am not able to save the new image that I selected to replace the old one. This is how I tried to do it and it only saves the file on the current state and not to parse. This is the code that I have currently and it is not working the way I want it to. Kindly assist.
Code is as follows
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(pickedImage);
Bitmap selectedImages = BitmapFactory.decodeStream(inputStream);
imageSelected.setImageBitmap(selectedImages);
selectedImages = ((BitmapDrawable) imageSelected.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImages.compress(Bitmap.CompressFormat.PNG, 5, stream);
byte[] imageRec = stream.toByteArray();
file = new ParseFile("profileUpdate.png", imageRec);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (null == e)
currentUser.put("ProfilePicture", file);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Unable to load image",
Toast.LENGTH_LONG).show();
}
}
}
}
I just added the currentUser.saveInBackground(); line after currentUser.put("ProfilePicture", file); and added a currentUser.remove("ProfilePicture"); before it and it worked.

Categories