[Android开发]-图片压缩(根据屏幕大小进行比例压缩)
在压缩图片后,将图片保存在外部缓存中。
public class MainActivity extends AppCompatActivity {
private Bitmap bitmap;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image_view);
// 获取屏幕的宽高
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
int screenWidth = mDisplayMetrics.widthPixels;
int screenHeight = mDisplayMetrics.heightPixels;
// 只编码模式,获取图片的属性,如图片尺寸、类型,但不加载图片
mOptions.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.mipmap.image, mOptions);
// 得到图片的宽高
int outWidth = mOptions.outWidth;
int outHeight = mOptions.outHeight;
Log.i("onCreate: ", "------outWidth: " + outWidth + "------outHeight: " + outHeight);
// 宽高的缩放比例
int widthScale = Math.round((float) outWidth / screenWidth);
int heightScale = Math.round((float) outHeight / screenHeight);
// 得到图片的压缩比例
int sampleSize = 0;
if (outWidth > outHeight) {
sampleSize = widthScale;
Log.i("onCreate: ", "------widthScale: " + widthScale);
} else {
sampleSize = heightScale;
Log.i("onCreate: ", "------heightScale: " + heightScale);
}
if (sampleSize > 1) {
mOptions.inSampleSize = sampleSize; // 设置图片的压缩比例
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
mOptions.inJustDecodeBounds = false; // 退出只编码模式
bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image, mOptions);
}
// 显示压缩后的图片
imageView.setImageBitmap(bitmap);
// 将压缩后的图片保存
try {
FileOutputStream fos = new FileOutputStream(new File(getExternalCacheDir(), "img.jpg"));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }