我想将从相机拍摄的照片发送到服务器。但它的大小约为 1M,我相信它是两个多。因此我想减小照片的大小。下面是我正在使用的方法。
saveFile
- 只需将位图保存到文件并返回路径即可。
calculateInSampleSize
返回inSampleSize
以将照片描述调整为已选择。
decodeSampledBitmapFromResource
从文件中解码 birmap 并使用新参数重建它。
一切都很好,但似乎不起作用。small3.png 的尺寸为 1240*768*24,大小仍为 ~1M。
我称之为
photo = saveFile(decodeSampledBitmapFromResource(picturePath,
800, 800),3);
方法
public String saveFile(Bitmap bm,int id) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Mk";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "smaller" + id + ".png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file.getPath();
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String path,
int reqWidth, int reqHeight) {
Log.d("path", path);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}