I have followed some tutorials about opening gallery and selecting and image and then displaying the image and file size. At the moment It doesnt seem to actually properly get the file size, i dont know if this is because of incorrect permissions or so on. Attached is the onCreate, openGallery and onActivityResult code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askPermission();
imgOriginal = findViewById(R.id.imgOriginal);
imgCompressed = findViewById(R.id.imgCompressed);
txtOriginal = findViewById(R.id.txtOriginal);
txtCompressed = findViewById(R.id.txtCompressed);
txtQuality = findViewById(R.id.txtQuality);
txtHeight = findViewById(R.id.txtHeight);
txtWidth = findViewById(R.id.txtWidth);
seekBar = findViewById(R.id.seekQuality);
btnPick = findViewById(R.id.btnPick);
btnCompress = findViewById(R.id.btnCompress);
filepath = path.getAbsolutePath();
if (!path.exists()) {
path.mkdirs();
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
txtQuality.setText("Quality: " i);
seekBar.setMax(100);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
btnPick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openGallery();
}
});
btnCompress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int quality = seekBar.getProgress();
int width = Integer.parseInt(txtWidth.getText().toString());
//int height = Integer.parseInt(txtHeight.getText().toString());
int height = Integer.parseInt(txtHeight.getText().toString());
Toast.makeText(MainActivity.this, "Quality " quality, Toast.LENGTH_SHORT).show();
try {
compressedImage = new Compressor(MainActivity.this)
.setMaxWidth(width)
.setMaxHeight(height)
.setQuality(quality)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(filepath)
.compressToFile(originalImage);
File finalFile = new File(filepath, originalImage.getName());
Bitmap finalBitmap = BitmapFactory.decodeFile(finalFile.getAbsolutePath());
imgCompressed.setImageBitmap(finalBitmap);
txtCompressed.setText("size: " Formatter.formatShortFileSize(MainActivity.this, finalFile.length()));
//Toast.makeText(MainActivity.this, filepath " Something went Wrong", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error while Compressing", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, RESULT_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
btnCompress.setVisibility(View.VISIBLE);
final Uri imageUri = data.getData();
try {
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imgOriginal.setImageBitmap(selectedImage);
originalImage = new File(imageUri.getEncodedPath().replace("raw/", ""));
txtOriginal.setText("Size: " Formatter.formatShortFileSize(this, originalImage.length()));
Toast.makeText(MainActivity.this, "Size: " Formatter.formatShortFileSize(this, originalImage.length()), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
}
}
This is my permissions code, this could be where i am wrong...The tutorial recommended to use Dexter, but any other ways or help with dexter would be appreciated.
private void askPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
Dexter.withContext(this)
.withPermissions(Manifest.permission.MANAGE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE).withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
} else {
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
}
}
CodePudding user response:
if (result.getResultCode() == Activity.RESULT_OK ) {
// There are no request codes
Intent data = result.getData();
Uri selectedImage = data.getData();
if (isFileLessThan2MB(selectedImage) <= 2000000){ // 2mp = 2000000
Glide.with(getContext()).load(selectedImage).into(binding.addressuploadImg);
addressuri =selectedImage;
}else {
Toast.makeText(getContext(), "File Size Should below 2mp", Toast.LENGTH_SHORT).show();
}
}
private long isFileLessThan2MB(Uri file) {
Cursor returnCursor =
getActivity().getContentResolver().query(file, null, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* move to the first row in the Cursor, get the data,
* and display it.
*/
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
//
// nameView.setText(returnCursor.getString(nameIndex));
// sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));
return returnCursor.getLong(sizeIndex);
}
CodePudding user response:
The right way to get the file size for an Uri:
long size = DocumentFile.fromSingleUri(context,uri).length();