[フレーム]
Last Updated: November 27, 2022
·
74.17K
· alberovalley

Resize an image in android to a given width

High end android devices can take great pictures. But great also means big, and sometimes you need them to have a limited width. Following snippet will get you that result.

// we'll start with the original picture already open to a file
File imgFileOrig = getPic(); //change "getPic()" for whatever you need to open the image file.
Bitmap b = BitmapFactory.decodeFile(imgFileOrig.getAbsolutePath());
// original measurements
int origWidth = b.getWidth();
int origHeight = b.getHeight();

final int destWidth = 600;//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();
}

AltStyle によって変換されたページ (->オリジナル) /