• 安卓图片代码压缩(效果简直爆炸)


    话不多说,直接上代码,主函数中直接怼两个方法进去,复制粘贴即可

     //图片压缩功能获取长宽比
        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的值,这样可以保证最终图片的宽和高
                // 一定都会大于等于目标的宽和高。
                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
            return inSampleSize;
        }
        //图片压缩功能
        public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                             int reqWidth, int reqHeight) {
            // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(res, resId, options);
            // 调用上面定义的方法计算inSampleSize值
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            // 使用获取到的inSampleSize值再次解析图片
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeResource(res, resId, options);
        }

    方法调用,哪里要图片就塞哪里,直接把图片给你整成100*100

    imageView.setImageBitmap(
                        decodeSampledBitmapFromResource(getResources(), imgs[position], 100, 100));
  • 相关阅读:
    python编程学习进度二
    python编程学习进度一
    阅读笔记(6)-《高效程序员的45个习惯》
    阅读笔记(5)-《高效程序员的45个习惯》
    阅读笔记(4)-《高效程序员的45个习惯》
    阅读笔记(3)-《高效程序员的45个习惯》
    阅读笔记(2)-《高效程序员的45个习惯》
    寒假生活15
    寒假生活14(补)
    寒假生活13
  • 原文地址:https://www.cnblogs.com/ShaoXin/p/6203634.html
Copyright © 2020-2023  润新知