I am trying to upload an image in firebase storage and I want that the image should not be bigger than 50 kb I am trying to get the size of the bitmap so that I can know if the bitmap's size is more than 50 kb the image would not be shown for the gallery I have tried many codes that were suggested by many people but none of them worked for me. Please help me in solving this problem. Here is my code:
@Override
protected void onActivityResult( int requestCode , int resultCode , @Nullable Intent data )
{
super.onActivityResult (requestCode , resultCode , data);
if(requestCode == ChooseImage && resultCode == RESULT_OK && data != null && data.getData() != null){
userProfileImage = data.getData ();
try {
Bitmap bitmap=MediaStore.Images.Media.getBitmap (getContentResolver ( ) , userProfileImage);
if (bitmap.getHeight () * bitmap.getRowBytes () < 50000)
profile_photo.setImageBitmap (bitmap);
btn.setOnClickListener (new View.OnClickListener ( ) {
@Override
public void onClick( View v ) {
uploaImage ();
}
});
} catch (IOException e) {
e.printStackTrace ( );
Toast.makeText (this , e.getMessage () , Toast.LENGTH_SHORT).show ( );
}
}
}
try this code:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (requestCode == ChooseImage && resultCode == RESULT_OK && data != null && data.getData() != null) {
userProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), userProfileImage);
if (bitmap.getHeight() * bitmap.getRowBytes() < 50000)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long bitmap_size = imageInByte.length / 1024;
profile_photo.setImageBitmap(bitmap);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploaImage();
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
long variable bitmap_size
will give you image size in KB
You can use this code to get size in KB:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long sizeInKB = imageInByte.length / 1024; //Size in KB
Thank you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.