Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

Re-size and Compress Image in Android Studio

In this post, we will learn how to resize and compress an image in Android. Resize image will give usefull in some time.

Bitmap b = BitmapFactory.decodeFile("Pass your file path");
// original measurements
int origWidth = b.getWidth();
int origHeight = b.getHeight();

final int destWidth = 500;//or the width you need

if(origWidth > destWidth){
         // picture is wider than we want it, we calculate its target height
          int destHeight = origHeight/( origWidth / destWidth ) ;
         // we create an scaled bitmap so it reduces the image, not just trim it
          Bitmap b2 = Bitmap.createScaledBitmap(b, destWidth, destHeight, false);
          ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            // compress to the format you want, JPEG, PNG... 
            // 70 is the 0-100 quality percentage
    b2.compress(Bitmap.CompressFormat.JPEG,70 , outStream);
            // we save the file, at least until we have made use of it
           File f = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "test.jpg");
           f.createNewFile();
           //write the bytes in file
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(outStream.toByteArray());
           // remember close de FileOutput
    fo.close();
}

 

With the above coe we can resize image from given file.

 

How to rotate Bitmap in Android?

We can rotate given bitmap by below functionality

Bitmap RotateBitmap(Bitmap source, float angle)
    {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }

 

in the above method pass bitmap which we need to ratate and pass rotation angle

 

Generate Bitmap from drawable image

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
// Resize the bitmap to 150x100 (width x height)
Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 150, 100, true);

 

 

References:


590 Views

Author: RRTutors