图片工具类【utils】【glide加载圆角】【ImageUtils】

废话不多说,拷贝就可以直接用

package com.wanlang.base.base_utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.ColorDrawable;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.wanlang.base.BaseApplication;
import com.wanlang.wanandroid.R;

import java.io.IOException;
import java.security.MessageDigest;

import androidx.annotation.NonNull;

/**
 * 图片工具类
 */
public class ImageUtils {
    /**
     * 加载网络图片
     */
    public static void loadImage(ImageView imageView, Object url) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.logo_app);    //图片加载出来前,显示的图片
        //                .error(R.mipmap.error)                  //图片加载失败后,显示的图片
        //                .fallback(R.mipmap.tab_me_bg);          //url为空的时候,显示的图片
        DrawableCrossFadeFactory drawableCrossFadeFactory = new DrawableCrossFadeFactory
                .Builder(300)
                .setCrossFadeEnabled(true)
                .build();
        Context context;
        if (imageView == null) {
            return;
        } else {
            if (imageView.getContext() == null) {
                context = BaseApplication.Companion.getContext();
            } else {
                context = imageView.getContext();
            }
            Glide.with(context)
                    .load(url)
                    .apply(options)
//                    .centerCrop()//centerCrop()是将图片按照比例放大到imageview的尺寸;
                    .centerCrop()//fitCenter()是将图片按照比例缩小到imageview的尺寸;
//                    .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))//设置加载动画
                    .into(imageView);
        }
    }

    /**
     * 加载圆角图片
     *
     * @param imageView
     * @param url       链接地址
     * @param dp        圆角大小
     */
    public static void loadImageCircle(Context context, ImageView imageView, Object url, int dp) {
        //设置图片大小
        RoundedCorners roundedCorners = new RoundedCorners(dp);
        //通过RequestOptions扩展功能,
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners)
                .placeholder(new ColorDrawable(Color.GRAY))//设置占位图
                .error(R.mipmap.logo_app)//设置错误图片
                .fallback(new ColorDrawable(Color.RED))
                .override(300, 300);//采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗

        Glide.with(context)
                .asBitmap()
                .load(url)
                .apply(options)
                //fixme 注意加载圆角的时候,注释掉下面的方法
//                .centerCrop()//centerCrop()是将图片按照比例放大到imageview的尺寸;
//                .fitCenter()//fitCenter()是将图片按照比例缩小到imageview的尺寸;
                .into(imageView);
    }

    /**
     * 加载圆形
     */
    public static void loadImageCircle(Context context, ImageView imageView, String url) {
        Glide.with(context)
                .load(url)
                .apply(RequestOptions.circleCropTransform()
                        .placeholder(new ColorDrawable(Color.GRAY))
                        .error(new ColorDrawable(Color.WHITE))
                        .fallback(new ColorDrawable(Color.RED)))
                .into(imageView);
    }

    /**
     * 加载网络图片
     */
    public static void loadImageBannerDefault(ImageView imageView, String url) {
        if (TextUtils.isEmpty(url)) {

        } else {
            Glide.with(imageView.getContext())
                    .load(url)
                    .apply(new RequestOptions()
                            .placeholder(new ColorDrawable(Color.GRAY))
                            .error(R.mipmap.logo_app)
                            .fallback(new ColorDrawable(Color.RED)))
                    .into(imageView);
        }

    }

    /**
     * 根据路径获得图片信息并按比例压缩,返回bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿,获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, 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;
    }

    /**
     * 获取照片角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转照片
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    private static class RoundedCornersTransform implements Transformation {
        private BitmapPool mBitmapPool;

        private float radius;

        private boolean isLeftTop, isRightTop, isLeftBottom, isRightBotoom;

        /**
         * 需要设置圆角的部分
         *
         * @param leftTop     左上角
         * @param rightTop    右上角
         * @param leftBottom  左下角
         * @param rightBottom 右下角
         */
        public void setNeedCorner(boolean leftTop, boolean rightTop, boolean leftBottom, boolean rightBottom) {
            isLeftTop = leftTop;
            isRightTop = rightTop;
            isLeftBottom = leftBottom;
            isRightBotoom = rightBottom;
        }

        /**
         * @param context 上下文
         * @param radius  圆角幅度
         */
        public RoundedCornersTransform(Context context, float radius) {
            this.mBitmapPool = Glide.get(context).getBitmapPool();
            this.radius = radius;
        }

        @NonNull
        @Override
        public Resource transform(@NonNull Context context, @NonNull Resource resource, int outWidth, int outHeight) {
            Bitmap source = resource.get();
            int finalWidth, finalHeight;
            //输出目标的宽高或高宽比例
            float scale;
            if (outWidth > outHeight) {
                //如果 输出宽度 > 输出高度 求高宽比
                scale = (float) outHeight / (float) outWidth;
                finalWidth = source.getWidth();
                //固定原图宽度,求最终高度
                finalHeight = (int) ((float) source.getWidth() * scale);
                if (finalHeight > source.getHeight()) {
                    //如果 求出的最终高度 > 原图高度 求宽高比
                    scale = (float) outWidth / (float) outHeight;
                    finalHeight = source.getHeight();
                    //固定原图高度,求最终宽度
                    finalWidth = (int) ((float) source.getHeight() * scale);
                }
            } else if (outWidth < outHeight) {
                //如果 输出宽度 < 输出高度 求宽高比

                scale = (float) outWidth / (float) outHeight;
                finalHeight = source.getHeight();
                //固定原图高度,求最终宽度
                finalWidth = (int) ((float) source.getHeight() * scale);
                if (finalWidth > source.getWidth()) {
                    //如果 求出的最终宽度 > 原图宽度 求高宽比

                    scale = (float) outHeight / (float) outWidth;
                    finalWidth = source.getWidth();
                    finalHeight = (int) ((float) source.getWidth() * scale);
                }
            } else {
                //如果 输出宽度=输出高度
                finalHeight = source.getHeight();
                finalWidth = finalHeight;
            }

            //修正圆角
            this.radius *= (float) finalHeight / (float) outHeight;
            Bitmap outBitmap = this.mBitmapPool.get(finalWidth, finalHeight, Bitmap.Config.ARGB_8888);
            if (outBitmap == null) {
                outBitmap = Bitmap.createBitmap(finalWidth, finalHeight, Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(outBitmap);
            Paint paint = new Paint();
            //关联画笔绘制的原图bitmap
            BitmapShader shader = new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            //计算中心位置,进行偏移
            int width = (source.getWidth() - finalWidth) / 2;
            int height = (source.getHeight() - finalHeight) / 2;
            if (width != 0 || height != 0) {
                Matrix matrix = new Matrix();
                matrix.setTranslate((float) (-width), (float) (-height));
                shader.setLocalMatrix(matrix);
            }

            paint.setShader(shader);
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0.0F, 0.0F, (float) canvas.getWidth(), (float) canvas.getHeight());
            //先绘制圆角矩形
            canvas.drawRoundRect(rectF, this.radius, this.radius, paint);

            //左上角圆角
            if (!isLeftTop) {
                canvas.drawRect(0, 0, radius, radius, paint);
            }
            //右上角圆角
            if (!isRightTop) {
                canvas.drawRect(canvas.getWidth() - radius, 0, canvas.getWidth(), radius, paint);
            }
            //左下角圆角
            if (!isLeftBottom) {
                canvas.drawRect(0, canvas.getHeight() - radius, radius, canvas.getHeight(), paint);
            }
            //右下角圆角
            if (!isRightBotoom) {
                canvas.drawRect(canvas.getWidth() - radius, canvas.getHeight() - radius, canvas.getWidth(), canvas.getHeight(), paint);
            }

            return BitmapResource.obtain(outBitmap, this.mBitmapPool);
        }


        @Override
        public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        }
    }
}

 

你可能感兴趣的:(图像选择(包括二维码),技术总结,使用技巧)