`
ch_kexin
  • 浏览: 877326 次
  • 性别: Icon_minigender_2
  • 来自: 青岛
社区版块
存档分类
最新评论

android BitmapUtils

 
阅读更多
package com.rangergame.yanheji_guiji.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * author : makenna
 * time   : 2020/11/14
 * describe   :Bitmap工具类
 */
public class BitmapUtils {
    private static String TAG="tag";
    /**
     * 根据文件名,从Assets中取图片
     *
     * @param context
     * @param fileName
     *            例如:game_bg.png
     * @return
     */
    public static Bitmap getBitmapFromAsset(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;
    }

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

        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(filename);
        } 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;
    }

    /**
     * 根据URL下载图片
     *
     * @param imageUrl
     *            网络url地址
     * @param connectTimeout
     *            链接超时
     * @param readTimeout
     *            读取超时
     * @return
     */
    public static Bitmap downloadPic(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;
    }

    /**
     * 更改bitmap的宽,高
     *
     * @param bmp
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static Bitmap resizeBitmap(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 resizeBitmap(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;
    }

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

    /**
     * 处理头像(填充圆角)
     *
     * @param bitmap
     * @param roundPx
     * @return
     */
    public static Bitmap getCornerBitmap(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;
    }

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

        Bitmap bitmapWithReflection = null;
        try {

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

            Matrix matrix = new Matrix();

            matrix.preScale(1, -1);

            Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 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(originalImage, 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 = originalImage;
            //
            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 {@link #SUCCESS} or {@value #OUT_OF_BOUNDS_EXCEPTION}
     */
    public static boolean mosaic(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;
//			int[] srcData = srcBitmap.mBuffer;

            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) {
            // 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;
    }


    /**
     * 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 {@link #SUCCESS} or {@value #OUT_OF_BOUNDS_EXCEPTION}
     */
    public static boolean mosaic2(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 dstData = 0;
            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;
                    }
                    srcData = srcBitmap.getPixel(srcX, srcY);
                    dstBitmap.setPixel(i, j, srcData);
//					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) {
            // 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;
        }
    }

}

 

分享到:
评论

相关推荐

    Android BitmapUtils工具类使用详解

    主要为大家详细介绍了Android BitmapUtils工具类的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    Android图片处理工具类BitmapUtils

    Android图片的处理工具类BitmapUtils,供大家参考,具体内容如下 项目中经常会用到图片,所以在这先简单的总结一下。闲言少叙,上代码。 package com.lvstudio.myapp.utils; import android.content.Context; ...

    BitmapUtils工具类

    自定义的bitmap处理工具类

    一个简单的开源Android工具类库

    BitmapUtils Bitmap Unility Class BlurUtils Blur Unility Class ByteUtils Byte Unility Class CalendarUtils Calendar Unility Class ClipboardUtils Clipboard Unility Class CollectionUtils Collection ...

    Android代码-AndroidCommon

    BitmapUtils Bitmap Unility Class BlurUtils Blur Unility Class ByteUtils Byte Unility Class CalendarUtils Calendar Unility Class ClipboardUtils Clipboard Unility Class CollectionUtils ...

    很牛逼的android开发包

    BitmapUtils模块: 加载bitmap的时候无需考虑bitmap加载过程中出现的oom和android容器快速滑动时候出现的图片错位等现象; 支持加载网络图片和本地图片; 内存管理使用lru算法,更好的管理bitmap内存; 可配置线程...

    BitmapUtils.java

    Android对bmp文件的读写支持不好,该工具类是把Bitmap图片保存成8bit灰度bmp图片的工具类

    android最火开源库xUtils源码

    android最火开源库xUtils源码, DbUtils模块,ViewUtils模块,HttpUtils,BitmapUtils。

    imagecycleview:自定义图片自动轮播控件,自定轮播指示器样式,支持点击,无限轮播,网络下载图片。 可是使用XUtil的BitmapUtils也可是使用smart-image-view加载图片,支持轮播文字切换.此插件是基于viewpager实现的,需要导入android-support-v4.jar

    自定义图片自动轮播控件,自定轮播指示器样式,支持点击,无限轮播,网络下载图片可是使用XUtil的BitmapUtils也可是使用smart-image-view加载图片,支持轮播文字切换此插件是基于viewpager实现的,需要导入android-...

    xUtils android开发框架

    * BitmapUtils模块: &gt; * 加载bitmap的时候无需考虑bitmap加载过程中出现的oom和android容器快速滑动时候出现的图片错位等现象; &gt; * 支持加载网络图片和本地图片; &gt; * 内存管理使用lru算法,更好的管理bitmap...

    Android快速开发框架xUtils-2.6.14

    三 BitmapUtils 你的程序因OOM强制关闭过嘛 你在为加在网络图片头疼嘛 有了组件 你将永久摆脱前面的问题 四 DbUtils 简单易用又出色的ORM框架 真的是谁用谁知道 直接轻松存储各种对象到sqlite数据库中 同时也能...

    Android代码-CommonLibary

    CommonLibrary主要是自己整理的一些项目开发中常用的工具类、通用UI的集合,目前在不断的更新中,尽可能的覆盖Android开发中通用的一些东西 。 &gt; anim &gt; -- AnimationUtils、ViewAnimationUtils。动画工具类,也可...

    定义图片自动图片轮播器.zip

    可是使用XUtil的BitmapUtils也可是使用smart-image-view加载图片,支持轮播文字切换 此插件是基于viewpager实现的,需要导入android-support-v4.jar 如果使用网络图片记得加权限。 uses-permission android:name=...

    Android 实现将Bitmap 保存到本地

    Overview 图片是一个可以使你程序变得比较的美观,所以我们会在我们的软件中使用图片。但是对于图片的操作也是比较的复杂。...class BitmapUtils { /** * Save Bitmap * * @param name file name

    android获取网络图片

    android获取网络图片,根据url来下载图片并展示在imageview上面,主要写了两种方式,一种是常规的请求获取,一种是使用第三方的类库xutils的bitmaputils来获取图片

    Android-Android工具类集合

    工具类集合,包括BitmapUtils、DeviceUtils、HttpURLConnectionUtils、LogUtils、ManifestUtils、MD5Utils、NetworkUtils、StringUtils、ToastUtils、FileUtils、ResourceUtils、ZipUtils、CacheUtils、...

    新闻客户端源码(安卓)

     该新闻用到的知识模块有:android高级界面设计(Fragment、ViewPager),android网络通信(http通信),开源组件(xutils框架-HttpUtils模块、xutils框架-BitmapUtils模块),开源框架(library)。所需jar包:...

    Android实现调用系统图库与相机设置头像并保存在本地及服务器

    废话不多说了,直接给大家贴代码了,具体代码如下所述: /** * 1、实现原理:用户打开相册或相机选择相片后,相片经过压缩并设置在控件上,图片在... * &lt;uses android:name=android.permission.INTERNET&gt;&lt;/uses-permi

Global site tag (gtag.js) - Google Analytics