图片质量压缩笔记

    xiaoxiao2021-03-25  159

    /** * 根据路径压缩图片上传 * @param path * @param imageSize * @param reqWidth * @param reqHeight * @return */ public static Bitmap compressImage(String path,int imageSize,int reqWidth, int reqHeight) { Bitmap bitmaps=getSmallBitmaped(path,reqWidth,reqHeight); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmaps.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while ( baos.toByteArray().length / 1024>imageSize) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset();//重置baos即清空baos bitmaps.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 options -= 10;//每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 return bitmap; } /** * 根据路径获得图片并压缩尺寸,返回bitmap用于显示 */ public static Bitmap getSmallBitmaped(String path, int reqWidth, int reqHeight) { 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); } /** * 计算图片的缩放值 */ 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 heightRatio = Math.round((float) height/ (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }
    转载请注明原文地址: https://ju.6miu.com/read-2602.html

    最新回复(0)