Redimensione uma imagem no Android para uma determinada largura

Dispositivos Android de última geração podem tirar ótimas fotos. Mas grande também significa grande , e às vezes você precisa que eles tenham uma largura limitada. O snippet a seguir obterá esse resultado.

// 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();
}