How can I compress the file size and quality when uploading pictures?
I already finished the upload file to firebase, how to compress the file?
Because when the file size is big, it will slow loading in recyclerview.
So I wanna compress the file.
Uri imageUri = imageListUri.get(index);
if(spinner.getSelectedItem().toString().equals(getApplicationContext().getResources().getString(R.string.choose_sub))) {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle(getApplicationContext().getResources().getString(R.string.alert_error))
.setMessage(getApplicationContext().getResources().getString(R.string.choose_sub))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
alertDialog.show();
} else if(image_check.equals("ok")) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getApplicationContext().getResources().getString(R.string.posting));
progressDialog.show();
if (imageUri != null) {
final StorageReference filerefrence = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
// scaling the image
int scaleDivider = 1;
try {
Bitmap fullBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
int scaleWidth = fullBitmap.getWidth() / scaleDivider;
int scaleHeight = fullBitmap.getHeight() / scaleDivider;
byte[] downsizedImageBytes =
getDownsizedImageBytes(fullBitmap, scaleWidth, scaleHeight);
uploadTask = filerefrence.putBytes(downsizedImageBytes);
} catch (IOException e) {
e.printStackTrace();
}
static public byte[] getDownsizedImageBytes(Bitmap fullBitmap, int scaleWidth, int scaleHeight) throws IOException {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(fullBitmap, scaleWidth, scaleHeight, true);
// 2. Instantiate the downsized image content as a byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
return baos.toByteArray();
}
So, is it correct?
try {
Bitmap fullBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
ByteArrayOutputStream out = new ByteArrayOutputStream();
fullBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); // Here 100 is the quality in percent of the image
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
int scaleWidth = fullBitmap.getWidth() / scaleDivider;
int scaleHeight = fullBitmap.getHeight() / scaleDivider;
byte[] downsizedImageBytes =
getDownsizedImageBytes(fullBitmap, scaleWidth, scaleHeight);
uploadTask = filerefrence.putBytes(downsizedImageBytes);
} catch (IOException e) {
e.printStackTrace();
}