Android BitmapUtil Bitmap读取、保存、下载、效果处理

Android BitmapUtil 工具类整理,包含的功能:

  • 读取 Bitmap:
    从Sdcard读取图片、从Assets中去取图片;
  • 保存 Bitmap:
    将View截图为Sdcard的一张图片;
    将Bitmap保存为Sdcard的一张图片;
  • 下载 Bitmap:
    根据URL地址,从网络侧下载Bitmap;
  • 处理 Bitmap:
    Bitmap宽高更改、Bitmap等比缩放、Bitmap增加圆角、Bitmap镜像;
public class BitmapUtil {
    private static final String TAG = "BitmapUtil";

    // ############################################################

    /**
     * 根据路径,以流的形式,在sdcard中读取图片
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBmpFromSdcard(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }

        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(filePath);
        } catch (OutOfMemoryError e) {
            if (bitmap != null) {
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                }
                bitmap = null;
            }
        } catch (Exception e) {
            if (bitmap != null) {
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                }
                bitmap = null;
            }
        }
        return bitmap;
    }


    /**
     * 根据文件名,从Assets中取图片
     *
     * @param context
     * @param fileName 例如:game_bg.png
     * @return
     */
    public static Bitmap getBmpFromAssets(Context context, String fileName) {
        Bitmap bmp = null;
        if (TextUtils.isEmpty(fileName)) {
            return null;
        }
        AssetManager asm = context.getAssets();
        if (asm == null) {
            return bmp;
        }
        InputStream is = null;
        try {
            is = asm.open(fileName);
            bmp = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bmp;
    }

    // ############################################################

    /**
     * 将当前的View 截图保存为sdcard的一张 PNG 图片
     */
    public static void saveViewToSdcard(View view, String pngFilePath) {
        FileOutputStream out = null;
        try {
            File file = new File(pngFilePath);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            //
            out = new FileOutputStream(file);
            view.setDrawingCacheEnabled(true);
            view.buildDrawingCache();
            //
            Bitmap bitmap = view.getDrawingCache();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            view.destroyDrawingCache();
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                }
            }
        }
    }


    /**
     * 将图片存入Sdcard中指定路径
     *
     * @param bitmap
     * @param pngFilePath
     * @return
     */
    public static boolean saveBmpToSdcard(Bitmap bitmap, String pngFilePath) {
        if (bitmap == null || TextUtils.isEmpty(pngFilePath)) {
            return false;
        }
        File file = null;
        FileOutputStream fos = null;
        try {
            file = new File(pngFilePath);
            if (file.exists()) {
                file.delete();
            }
            //
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            return true;
        } catch (Exception e) {
            //
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (Exception e) {
                }
            }
        }
        return false;
    }


    // ############################################################


    /**
     * 更改bitmap的宽,高
     *
     * @param bmp
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static Bitmap resizeBmp(Bitmap bmp, int targetWidth,
                                   int targetHeight) {

        if (bmp == null || bmp.isRecycled()) {
            return null;
        }
        Bitmap bmResult = null;
        try {
            // 原始图片宽度
            float width = bmp.getWidth();
            // 原始图片高度
            float height = bmp.getHeight();

            Matrix m1 = new Matrix();
            // 这里指的是目标区域(不是目标图片)
            m1.postScale(targetWidth / width, targetHeight / height);
            // 声明位图
            bmResult = Bitmap.createBitmap(bmp, 0, 0, (int) width,
                    (int) height, m1, true);

        } catch (Exception e) {
            if (bmResult != null) {
                if (!bmResult.isRecycled()) {
                    bmResult.recycle();
                    bmResult = null;
                }
            }
            bmResult = bmp;
        }
        return bmResult;
    }

    /**
     * 按某个比例缩放图片
     *
     * @param bmp
     * @param ratio
     * @return
     */
    public static Bitmap resizeBmp(Bitmap bmp, float ratio) {

        if (bmp == null || bmp.isRecycled()) {
            return null;
        }
        Bitmap bmResult = null;

        try {
            // 图片宽度
            float width = bmp.getWidth();
            // 图片高度
            float height = bmp.getHeight();

            Matrix m1 = new Matrix();
            m1.postScale(ratio, ratio);
            // 声明位图
            bmResult = Bitmap.createBitmap(bmp, 0, 0, (int) width,
                    (int) height, m1, true);

        } catch (Exception e) {
            if (bmResult != null) {
                if (!bmResult.isRecycled()) {
                    bmResult.recycle();
                    bmResult = null;
                }
            }
            bmResult = bmp;
        }

        return bmResult;
    }

    /**
     * 处理头像(填充圆角)
     *
     * @param bitmap
     * @param roundPx
     * @return
     */
    public static Bitmap getCornerBmp(Bitmap bitmap, float roundPx) {
        if (bitmap == null) {
            return null;
        }
        Bitmap output = null;

        try {
            output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                    Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(rect);

            final Paint paint = new Paint();
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);

            return output;
        } catch (OutOfMemoryError e) {
            if (output != null) {
                if (!output.isRecycled()) {
                    output.recycle();
                    output = null;
                }
            }
            output = bitmap;
            //
            e.printStackTrace();

        }
        return null;
    }

    // ############################################################

    /**
     * 根据URL下载图片
     *
     * @param imageUrl       网络url地址
     * @param connectTimeout 链接超时
     * @param readTimeout    读取超时
     * @return
     */
    public static Bitmap downloadImg(String imageUrl, int connectTimeout,
                                     int readTimeout) {
        if (TextUtils.isEmpty(imageUrl)) {
            return null;
        }
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        Bitmap bitmap = null;
        try {

            url = new URL(imageUrl);
            conn = (HttpURLConnection) url.openConnection();
            //
            conn.setConnectTimeout(connectTimeout);
            //
            conn.setReadTimeout(readTimeout);
            conn.setDoInput(true);
            //
            conn.connect();
            is = conn.getInputStream();
            //
            bitmap = BitmapFactory.decodeStream(is);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    is = null;
                }
            }
        }
        return bitmap;
    }

    // ############################################################

    /**
     * 镜像效果mirror
     *
     * @param originalBmp
     * @return
     */
    public static Bitmap getMirrorBmp(Bitmap originalBmp) {
        if (originalBmp == null) {
            return null;
        }

        Bitmap bitmapWithReflection = null;
        try {

            final int reflectionGap = 2;
            int width = originalBmp.getWidth();
            int height = originalBmp.getHeight();

            Matrix matrix = new Matrix();

            matrix.preScale(1, -1);

            Bitmap reflectionImage = Bitmap.createBitmap(originalBmp, 0,
                    height / 2, width, height / 2, matrix, false);

            bitmapWithReflection = Bitmap.createBitmap(width,
                    (height + height / 6), Config.ARGB_8888);

            Canvas canvas = new Canvas(bitmapWithReflection);

            canvas.drawBitmap(originalBmp, 0, 0, null);

            canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

            Paint paint = new Paint();

            LinearGradient shader = new LinearGradient(0, height, 0,
                    bitmapWithReflection.getHeight() + reflectionGap + 20,
                    0xffffffff, 0x00ffffff, TileMode.MIRROR);

            paint.setShader(shader);
            paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

            canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                    + reflectionGap, paint);
        } catch (OutOfMemoryError e) {
            if (bitmapWithReflection != null) {
                if (!bitmapWithReflection.isRecycled()) {
                    bitmapWithReflection.recycle();
                    bitmapWithReflection = null;
                }
            }
            bitmapWithReflection = originalBmp;
            //
            e.printStackTrace();

        }
        return bitmapWithReflection;
    }

    /**
     * Mosaic a bitmap
     *
     * @param srcBitmap
     * @param radius    The pixel number of a block. such as width/16
     * @param dstBitmap the width and height must be the same of srcBitmap
     * @return
     */
    public static boolean mirrorBmp(final Bitmap srcBitmap, final int radius, Bitmap dstBitmap) {
        try {
            Log.d(TAG, "mosaic srcBitmap = " + srcBitmap + ", radius = " + radius + ", dstBitmap = " + dstBitmap);
            int w = srcBitmap.getWidth();
            int h = srcBitmap.getHeight();
            int[] srcData = new int[w * h];
            int[] dstData = new int[w * h];
            int midRadius = radius >> 1;
            int srcX, srcY;

            Log.d(TAG, "mosaic:w= " + w + ",h=" + h);
            long startTime = System.currentTimeMillis();
            srcBitmap.getPixels(srcData, 0, w, 0, 0, w, h);

            for (int j = 0; j < h; j++) {
                for (int i = 0; i < w; i++) {
                    srcX = i - i % radius + midRadius;
                    srcY = j - j % radius + midRadius;
                    if (srcX >= w) {
                        srcX = w - 1;
                    }
                    if (srcY >= h) {
                        srcY = h - 1;
                    }
                    dstData[j * w + i] = srcData[srcY * w + srcX];
                }
            }
            Log.d(TAG, "exe time = " + (System.currentTimeMillis() - startTime));
            dstBitmap.setPixels(dstData, 0, w, 0, 0, w, h);
            Log.d(TAG, "setPixels time = " + (System.currentTimeMillis() - startTime));

        } catch (ArrayIndexOutOfBoundsException e) {
            Log.e(TAG, "ArrayIndexOutOfBoundsException = " + e);
            return false;
        } catch (IllegalStateException e) {
            Log.e(TAG, "IllegalStateException = " + e);
            return false;
        } catch (Exception e) {
            Log.e(TAG, "Exception = " + e);
            return false;
        }

        return true;
    }


    /**
     * Mosaic2 a bitmap. The time cost is 9 times against as mosaic(...),
     * but the memory is half of it
     *
     * @param srcBitmap
     * @param radius    The pixel number of a block. such as width/16
     * @param dstBitmap the width and height must be the same of srcBitmap
     * @return
     */
    public static boolean mirrorBmp2(final Bitmap srcBitmap, final int radius, Bitmap dstBitmap) {
        try {
            Log.d(TAG, "mosaic srcBitmap = " + srcBitmap + ", radius = " + radius + ", dstBitmap = " + dstBitmap);
            int w = srcBitmap.getWidth();
            int h = srcBitmap.getHeight();
            int srcData = 0;
            int midRadius = radius >> 1;
            int srcX, srcY;

            Log.d(TAG, "mosaic:w= " + w + ",h=" + h);
            long startTime = System.currentTimeMillis();
            for (int j = 0; j < h; j++) {
                for (int i = 0; i < w; i++) {
                    srcX = i - i % radius + midRadius;
                    srcY = j - j % radius + midRadius;
                    if (srcX >= w) {
                        srcX = w - 1;
                    }
                    if (srcY >= h) {
                        srcY = h - 1;
                    }
                    srcData = srcBitmap.getPixel(srcX, srcY);
                    dstBitmap.setPixel(i, j, srcData);
                }
            }
            Log.d(TAG, "exe time = " + (System.currentTimeMillis() - startTime));
        } catch (ArrayIndexOutOfBoundsException e) {
            // TODO: handle exception
            Log.e(TAG, "ArrayIndexOutOfBoundsException = " + e);
            return false;
        } catch (IllegalStateException e) {
            Log.e(TAG, "IllegalStateException = " + e);
            return false;
        } catch (Exception e) {
            Log.e(TAG, "Exception = " + e);
            return false;
        }

        return true;
    }
    // ############################################################

    /**
     * 设置 ImageView 图标颜色
     */
    public void setImageViewColorFilter(ImageView view, int color) {
        if (view == null)
            return;
        view.setColorFilter(view.getContext().getResources().getColor(color));
    }

    /**
     * 获取 指定颜色 的图标
     *
     * @param context
     * @param resID
     * @return
     */
    public Drawable getThemeDrawableColorFilter(Context context, int resID, int color) {
        Drawable drawable = null;
        try {
            drawable = context.getResources().getDrawable(resID);
            drawable.setColorFilter(context.getResources().getColor(color), PorterDuff.Mode.SRC_ATOP);
        } catch (Exception | OutOfMemoryError error) {
            error.printStackTrace();
        }
        if (drawable == null) {
            return new ColorDrawable(Color.TRANSPARENT);
        } else {
            return drawable;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bjxiaxueliang

您的鼓励是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值