//直接调用getimage,参数为:路径、宽、高 public static Bitmap getimage(String pathName, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); // 若要对图片进行压缩,必须先设置Option的inJustDecodeBounds为true才能进行Option的修改 options.inJustDecodeBounds = true; // 第一次decodeFile是获取到options.outHeight和options.outWidth BitmapFactory.decodeFile(pathName, options); // options.inSampleSize是图片的压缩比,例如原来大小是100*100,options.inSampleSize为1,则不变, // options.inSampleSize为2,则压缩成50*50 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 重新设置options.inJustDecodeBounds为false,不能修改option options.inJustDecodeBounds = false; // 根据options重新加载图片 Bitmap src = BitmapFactory.decodeFile(pathName, options); return src; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; }
安卓图片压缩处理的终极方法,适用于各种机型
最新推荐文章于 2024-09-11 07:51:15 发布