This question already has an answer here:
How resize image from gallery?
(1 answer)
Closed 3 years ago.
I need too display a image in ImageView and upload to server by fetching from gallery. I have got a problem that I should allow the user to send image file more than 500kb. How to restrict the user to choose below 500kb. Or is there any way to compress the Image to PNG format which I got form Uri. Please need a solution
My Code follows:
if(requestCode == Constants.SELECT_PICTURE && resultCode == RESULT_OK){
if(data != null)
{
photoUri = data.getData();
if (photoUri != null)
{
try {
bMap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
Bitmap bitMap = Bitmap.createScaledBitmap(bMap, 320, 480, false);
cabinImge.setImageBitmap(bitMap);
Utility.releaseImgViewMemory(cabinImge);
uploadImage(bitMap);
}catch(OutOfMemoryError e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
When you select an image from the gallery in your app, it will return a URI for that image. You can then retrive its size and apply calculation on that simply byte/1024
Related
I am fetching image from google drive through storage access framework and convert it in to a bitmap. It's working fine in my galaxy A5 running on marshmallow but in my redmi 6A running on Oreo bitmap is returned empty. My code is as below
uri = resultData.getData();
isImageFromGoogleDrive = "com.google.android.apps.docs.storage".equals(Objects.requireNonNull(uri).getAuthority());
if(isImageFromGoogleDrive){
InputStream inputStream;
try {
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
the value of bm is empty on redmi 6A Oreo
You can do like this:
if (resultCode == RESULT_OK && requestCode == SELECT_IMAGE_REQUEST_CODE) {
Uri selectedImageUri = imageReturnedIntent.getData();
try (InputStream inputStream = sender.getContentResolver().openInputStream(selectedImageUri )) {
Files.copy(inputStream, "your_path_here", StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
Toast.makeText(sender, "A problem has occurred while importing image", Toast.LENGTH_SHORT).show();
Log.e(TAG, "error copying files:" + ex.getMessage());
return;
}
}
You can't just take the image like you would do with one image from SDCARD, so you need to copy that file in the memory (temporary or not) using Streams. This code will copy the image to a path, then you can do what you want with it.
I trying to develop an android application that enables the user to add a picture from his gallery, it works fine and displays the picture in the image view.
the problem is I am trying to save this picture in MySQL database (not URL or path of it) I want to store as a blob.
I tried the below code to get the image from user's gallery and display it in the image view.
The attribute test2 is a string and it is what I save in the database
if (requestCode == GET_FROM_GALLERY && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
}
////// edit
Bitmap image = BitmapFactory.decodeFile(imagepath);
FinalBytes = getBytes(image); // this will be save in DB
Bitmap getIt = getBitmap(FinalBytes);
imgV.setImageBitmap(getIt);
imgV.setDrawingCacheEnabled(true);
imgV.buildDrawingCache();
Bitmap testbit = imgV.getDrawingCache();
ByteArrayOutputStream testbyte = new ByteArrayOutputStream();
testbit.compress(Bitmap.CompressFormat.JPEG, 100, testbyte);
testbyte2 = testbyte.toByteArray();
base64Image = Base64.encodeToString(testbyte2, Base64.DEFAULT);
I used below code for retrieving the image
byte[] decodedString = Base64.decode(Recipes[position].getRimage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.image.setImageBitmap(decodedByte);
But I am getting this message when decoding it.
illegalargumentexception bad base 64
please help I spent 2 days on this error
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 want to upload a photo from my camera directly into a drive folder:
OutputStream outputStream = result.getDriveContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
/* image is my Bitmap */
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
So im doing this and it's working. The problem is that my pictures in drive is in very low quality and i need to have a High Quality video.
I already tried this solution Converting bitmap to byteArray android
But then in Drive the photo wasnt recognize as media file and can't read it. I may have failed something.
EDIT: i've done exactly the same things that is there https://stackoverflow.com/a/13000774/6644403 and doing this way to get my Bitmap in ActivityResult :
try {
mBitmapToSave = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
} else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex) {}
}
Refer this link Upload large files to Google Drive using GD API for google drive Uploadation.
I wasnt asking for rights to WRITE_EXTERNAL_STORAGE, it was in my manifest but since api23 i need to explicit and ask if the user ok.
Now it's good.
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.