Android の画像解像度と品質の最適化

画像パフォーマンスの最適化の読者は、画像の最適化の原理も理解する必要があるため、コードを直接アップロードして、将来の使用に備えて記録してください。

/**
     * 加载资源图片
     * @param context 上下文
     * @param inDraRes 图片资源id
     * @param iv 装载图片View
     * @param radius 圆角大小
     */
    public static void loadAndCompressImg(Context context, @DrawableRes int inDraRes, ImageView iv, int radius) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;
        BitmapFactory.decodeResource(context.getResources(), inDraRes, options);

        int inSampleSize = 1;
        int srcWidth = options.outWidth;
        int srcHeight = options.outHeight;
        srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
        srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;

        int longSide = Math.max(srcWidth, srcHeight);
        int shortSide = Math.min(srcWidth, srcHeight);

        /**
         * 如分辨率1920*1080中,宽高中最长/短=0.5625
         * 以下算法是计算inSampleSize值,对Bitmap图片质量和分辨率进行调整优化
         */
        float scale = ((float) shortSide / longSide);
        if (scale <= 1 && scale > 0.5625) {
            if (longSide < 4990) {
                inSampleSize = 2;
            } else if (longSide > 4990 && longSide < 10240) {
                inSampleSize = 4;
            } else {
                inSampleSize = longSide / 1280;
            }
        } else if (scale <= 0.5625 && scale > 0.5) {
            inSampleSize = longSide / 1280 == 0 ? 1 : longSide / 1280;
        } else {
            inSampleSize = (int) Math.ceil(longSide / (1280.0 / scale));
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        options.inSampleSize = inSampleSize;
        options.inJustDecodeBounds = false;
        Bitmap tagBitmap = BitmapFactory.decodeResource(context.getResources(), inDraRes, options);
        tagBitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
        tagBitmap.recycle();

        byte[] imgBytes = stream.toByteArray();
        try {
            stream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.ic_load_error)
                .error(R.drawable.ic_load_error)
                .transform(new GlideRoundTransform(context, radius))
                .dontAnimate();
        Glide.with(context).load(imgBytes).apply(requestOptions).into(iv);
    }

おすすめ

転載: blog.csdn.net/weixin_44715716/article/details/131573132