Android - Bitmap

一、概念

1.1 图像

  • 图片的大小(内存占用) =宽*高*单个像素点占用内存+图片属性信息。同一设备上,图片占用内存跟drawable目录分辨率大小变化成正比。同一drawable目录,图片占用内存跟设备分辨率大小成正比。

  • 色深:某分辨率下一个像素能接受的颜色数量,用2ⁿ来表示,8bit就是2的8次方。

  • DPI 和 PPI:都指的是每英寸长度上的点数。DPI用于打印机输出、鼠标的扫描取样等,PPI专用于显示器。

1.2 AndroidStudio文件夹

mipmap只是用来放应用图标的,避免在存放很多图片的 drawable 文件夹中找起来麻烦。

1.2.1 mipmap 文件夹

文件夹建议图标分辨率
mipmap-mdpi48*48
mipmap-hdpi72*72
mipmap-xhdpi96*96
mipmap-xxhdpi144*144
mipmap-xxxhdpi192*192

1.2.2 drawable 文件夹

如果系统没有在手机分辨率对应的 drawable 文件夹内找到图,就会往更高分辨率的文件夹去找,还找不到就会去 drawable-nodpi 中找,仍旧找不到就会去更低分辨率的文件夹中找。找到的图比目标分辨率大就缩小显示,反之会放大显示,这个倍数 = 高DPI / 低DPI,但 drawable-nodpi 中的图不会被缩放,是多大就显示多大。

DPI名称=范围值

分辨率名称=屏幕分辨率

density密度(1dp显示多少px)

0< ldpi ≤ 120

QVGA=240*320

0.75倍(120dpi/160=0.75px)

120< mdpi ≤ 160(基线)

HVGA=320*480

1倍(160dpi/160=1px)

160< hdpi ≤ 240

WVGA=480*800

FWVGA=480*854

1.5倍(240dpi/160=1.5px)

240< xhdpi ≤ 320

720P=720*1280

2倍(320dpi/160=2px)

320< xxhdpi ≤ 480

1080P=1080*1920

3倍(480dpi/160=3px)

480< xxxhdpi ≤ 640

4K=2460*3840

4倍(640dpi/160=4px)

//获取屏幕宽高的dpi
val xdpi = getResources().getDisplayMetrics().xdpi
val ydpi = getResources().getDisplayMetrics().ydpi

二、Bitmap

一个用来存储图像每个像素颜色信息的对象。通过它可以获取图像文件信息,进行图像颜色变换、剪切、旋转、缩放等操作,并可以指定格式保存图像文件。主要用于 ImageView 设置背景或当作 Canvas 画布使用。
imageView.setImageBitmap(bitmap)
val canvas: Canvas = Canvas(bitmap)

色彩配置 Bitmap.Config

描述了像素的存储方式,会影响色彩质量(色深)和透明度。

ALPHA_8

【只有透明度】每个像素只存储透明度没有颜色,适合用来遮盖如夜间模式,每个像素占8位(1个字节)。

RGB_565

【内存优化用】R(占5位)+G(占6位)+B(占5位) =一个像素占16位(2个字节)。

ARGB_8888

【占用内存多】A(占8位)+R(占8位)+G(占8位)+B(占8位) =一个像素占32位(4个字节)。(该项为默认项,Android 4.4以后RGB_565被废弃都会以该项执行)

ARGB_4444

【已废弃】 A(占4位)+R(占4位)+G(占4位)+B(占4位) =一个像素占16位(2个字节)。画质惨不忍睹已废弃,在Android 4.4以后即便设置了都会以ARGB_8888去执行。

压缩格式 Bitmap.CompressFormat

JEPG

以 JEPG 算法进行图像压缩,是一种有损压缩,quality压缩质量设置0-100值越小压缩越狠。不支持透明度会以黑色背景填充。

PNG

以 PNG 算法进行图像压缩,是一种无损压缩,会忽略0-100的quality压缩质量设置,支持透明度。

WEBP

【已废弃】以 WebP 算法进行有损压缩,quality压缩质量设置0-100值越小压缩越狠,Android 10开始设置100为无损压缩。已废弃,使用下面两个更明确的方式。

WEBP_LOSSY

以 WebP 算法进行有损压缩,quality压缩质量设置0-100值越压缩越狠越慢。体积比JEPG小40%但编码时间长8倍。

WEBP_LOSSLESS

以 WebP 算法进行无损压缩,quality压缩质量设置0-100值越压缩越狠越慢。体积比PNG小26%但编码时间长5倍。

2.1 创建

2.1.1 通过工厂 BitmapFactory.decodeXXX( )

从各种数据中创建位图,通过options实现获取图片信息、配置缩放比例。

public static Bitmap decodeFile(String pathName)

public static Bitmap decodeFile(String pathName, Options opts)

通过文件路径(SD卡)创建Bitmap。

public static Bitmap decodeStream(InputStream is)

public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)

通过输入流(网络、Assets)创建Bitmap。

public static Bitmap decodeResource(Resources res, int id)

public static Bitmap decodeResource(Resources res, int id, Options opts)

通过资源id(APP中)创建Bitmap。

public static Bitmap decodeByteArray(byte[] data, int offset, int length)

public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)

通过字节数组(二进制数据)创建Bitmap。

//资源文件(drawable/mipmap/raw)
val bitmap1 = BitmapFactory.decodeResource(context.resources, R.drawable.icon_weixin)
//资源文件(assets)
var bitmap2: Bitmap? = null
context.assets.open("XXX.png").use { inputStream ->
    bitmap2 = BitmapFactory.decodeStream(inputStream)
}
//SD卡文件
val path = Environment.getExternalStorageDirectory().path + "XXX.png"
val bitmap3 = BitmapFactory.decodeFile(path)

选项设置 BitmapFactory.Options

inJustDecodeBounds

设置为 true 时,decodeXXX( )只获取图片信息而不会将图片加载进内存 。

inSampleSize

采样率,通过对图像的宽高设置缩小比例以达到减少图片像素的目的,来避免OOM发生概率。若设置为4(每四个像素取一个返回而其它的舍弃)则宽高都为原来的1/4,图为原来的1/16。

outWidth

outHeight

outMimeType

获取图片的宽度。

获取图片的高度。

获取图片的MINE类型。

inDensity

inTargetDensity

给位图设置的密度。

绘制到新图上的密度。

inScaled

默认为true,inDensity和inTargetDensity不为0时会自动进行缩放以匹配inTargetDensity。

inPreferredConfig

设置色彩配置,默认是Bitmap.Config.ARGB_8888。

inMutable

inBitmap

设为true,使得Bitmap可被修改(支持重用)。

传入要被重用的Bitmap对象。

fun getBitmapFromFile(file: File, iv: ImageView): Bitmap {
    //仅解码边界(获取尺寸但不加载进内存)
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeFile(file.path, options)
    //计算缩放比例
    options.inSampleSize = calculateInSampleSize(options, iv)
    //再次解码
    options.inJustDecodeBounds = false  //取消
    return BitmapFactory.decodeFile(file.path, options)
}

fun calculateInSampleSize(options: BitmapFactory.Options, iv: ImageView): Int {
    //获取图片的宽高类型
    val picWidth = options.outWidth
    val picHeight = options.outHeight
    val picType = options.outMimeType
    //获取控件宽高
    val viewWidth = iv.measuredWidth
    val viewHeight = iv.measuredHeight
    //进行缩放计算
    var inSampleSize = 1
    if (picWidth > viewWidth || picHeight > viewHeight) {   //只要图片比控件大就缩放
        val widthRatio = picWidth / viewWidth
        val heightRatio = picHeight / viewHeight
        //选择最小比率,这样保证相差不大的那条边不至于图片缩得比控件还小
        inSampleSize = if (widthRatio < heightRatio) widthRatio else heightRatio
    }
    return inSampleSize
}

2.1.2 通过静态 Bitmap.createBitmap( )

对现有的位图进行处理后得到一个新的副本。(以下只列举参数最多的重载)

createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)

裁剪一个Bitmap。source是原图,x、y是新图第一个像素的坐标,width、height是新图的宽高(x+width、y+height不能超出原图的宽高),m是矩阵用来对新图进行平移/旋转/缩放/错切操作,filter是否给新图添加滤波效果

createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

缩放一个Bitmap,dstWidth 和 dstHeight 是新图宽高。

val matrix = Matrix().apply {
    postScale(0.8f, 0.9f)    //缩放(四参重载的后两位表示以该点为中心)
    postRotate(-45.21f) //旋转(负数为逆时针)
    postTranslate(100f, 80f) //移动
}
Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true)

2.2 处理

compress( )

boolean compress(CompressFormat format, int quality, OutputStream stream)

将位图压缩到指定的输出流,可看作将位图保存到文件中。quelity:0-100压缩质量,PNG无损会忽略该项。

copy( )

Bitmap copy(Config config, boolean isMutable)

创建一个副本,config色彩配置,isMutable是否可以修改新图像素值。

recycle( )

isRecycle( )

void recycle( )

回收位图占用的内存空间。

boolean isRecycled( )

判断位图内存是否已释放。

extractAlpha( )

Bitmap extractAlpha( )

创建一个只有透明度的副本,色彩配置为ALPHA_8。

getWidth( )

getHeight( )

int getWidth( )

获取位图的宽度。

int getHeight( )

获取位图的高度。

getByteCount( )

int getByteCount()

获取Bitmap的字节数。

isMutable( )

像素是否可修改。

getScaledWidth( )

getScaledHeight( )

获取指定密度转换后的图像宽度。

获取指定密度转换后的图像高度。

getByteCount()

getAllocationByteCount()

返回图片的大小。

返回Bitmap大小(因为可以复用,换成更小的图也还是占用原来的大小)。

三、内存优化

val maxMemory = Runtime.getRuntime().maxMemory() / 1024
println("获取每个APP最高可用内存大小:$maxMemory kb")
  • 一般图片来源是自己提供的只需要注意及时回收,如果是外部的,需要注意显示的时候缩小,以及异常捕获避免APP崩溃。

  • 一个进程可以简单分为 Java内存 和 Native内存。Bitmap对象在Java堆,像素数据在Native,不同Android版本的分配不同。Native的好处是共享整个手机的内存,不受单个APP分配的内存限制。

Android 2.3.3

API 10

Android 3.0~7.1

API 11~25

Android 8+

API 26+

Bitmap对象存放

Java堆

Java堆

Java堆

像素数据存放

Native

Java堆

Native

内存优化

bitmap.recycle( )

软引用

3.1 及时回收

不能保证立即就被回收,只是加快回收的到来。在确保该bitmap对象在代码中不会再使用的时候调用,一般在 onStop( ) 或 onDestroy( ) 中进行。一般不需要自己去干预GC。
if (bitmap != null && !bitmap.isRecycled) {
    bitmap.recycle()
    bitmap = null
}
System.gc()

3.2 缓存通用对象

例如用户未设置头像的默认图片,缓存在本地能减少流量消耗(DiskLruCache),缓存在内存能减少对象重复创建(LruCache)。

3.3 压缩后显示

在小小的控件上显示高分辨率图片不会提升多少视觉效果反而会占用很多内存,而系统分配给每个APP可用内存大小是固定的超出就会引起OOM内存溢出,因此在展示高分辨率图片的时候需要进行压缩以接近控件的大小来显示。(见上方代码)

  1. 在 decodeXXX() 时使用 BitmapFactory.Options 参数,将它的 inJustDecodeBounds = true 能禁止为 Bitmap 分配内存(返回null而不是Bitmap了)。
  2. 这样只会解码边界,会对 outWidth、outHeight、outMineType 属性进行赋值,也就拿到了图片的宽高和类型。
  3. 然后和控件的宽高进行缩放比例计算赋值给 inSampleSize。
  4. 再次调用 decodeXXX() 将 options参数的 inJustDecodeBounds  = false 后传入。

3.4 色彩编码配置

使用Bitmap.Config,将色彩配置设为低级别的RGB_565。

3.5 捕获异常

对创建 Bitmap 的代码进行 try-catch,即便OOM也不会闪退。

3.6 drawable文件夹

只有一套图的话, 按照最大众的 1080P 放在 drawable-xxhdpi 目录里。放在更低密度文件夹下,被放大意味着像素点变多占用更大内存,放在更高密度文件夹下,针对 2K 4K 设计的图片本身已经很大体积了,缩放也起不到多少节省内存的作用。

3.7 软引用

实现内存敏感的告诉缓存,内存空间不足时才回收这些对象的内存。

3.8 RecyclerView中内存复用

        当RecyclerView的Item移出页面之后,会放在缓存池当中;当下面的item显示的时候,首先会从缓存池中取出缓存,直接调用onBindViewHolder方法,所以依然会重新创建一个Bitmap,因此针对列表的缓存特性可以选择Bitmap内存复用机制,避免了频繁地创建Bitmap导致内存抖动。

        在BitmapFactory中提供了Options选项,当设置 inMutable=true,inBitmap = 要被复用的Bitmap对象,就代表开启了内存复用,此时新建的Bitmap只要小于等于要被复用的Bitmap,那么都会放在这块内存中,避免重复创建。

android Bitmap用法总结 Bitmap用法总结 1、Drawable → Bitmap public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); // canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } 2、从资源中获取Bitmap Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic); 3、Bitmap → byte[] private byte[] Bitmap2Bytes(Bitmap bm){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 4、byte[] → Bitmap private Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } 5、保存bitmap static boolean saveBitmap2file(Bitmap bmp,String filename){ CompressFormat format= Bitmap.CompressFormat.JPEG; int quality = 100; OutputStream stream = null; try { stream = new FileOutputStream("/sdcard/" + filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. e.printStackTrace(); } return bmp.compress(format, quality, stream); } 6、将图片按自己的要求缩放 // 图片源 Bitmap bm = BitmapFactory.decodeStream(getResources() .openRawResource(R.drawable.dog)); // 获得图片的宽高 int width = bm.getWidth(); int height = bm.getHeight(); // 设置想要的大小 int newWidth = 320; int newHeight = 480; // 计算缩放比例 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 取得想要缩放的matrix参数 Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的图片 Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); // 放在画布上 canvas.drawBitmap(newbm, 0, 0, paint); 相关知识链接:http://www.eoeandroid.com/thread-3162-1-1.html 7、bitmap的用法小结 BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = 2; //将图片设为原来宽高的1/2,防止内存溢出 Bitmap bm = BitmapFactory.decodeFile("",option);//文件流 URL url = new URL(""); InputStream is = url.openStream(); Bitmap bm = BitmapFactory.decodeStream(is); android:scaleType: android:scaleType是控制图片如何resized/moved来匹对ImageView的size。ImageView.ScaleType / android:scaleType值的意义区别: CENTER /center 按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分 显示 CENTER_CROP / centerCrop 按比例扩大图片的size居中显示,使得图片长(宽)等于或大于View的长 (宽) CENTER_INSIDE / centerInside 将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片 长/宽等于或小于View的长/宽 Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. FIT_CENTER / fitCenter 把图片按比例扩大/缩小到View的宽度,居中显示 FIT_END / fitEnd 把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置 FIT_START / fitStart 把图片按比例扩大/缩小到View的宽度,显示在View的上部分位置 FIT_XY / fitXY 把图片 不按比例 扩大/缩小到View的大小显示 MATRIX / matrix 用矩阵来绘制,动态缩小放大图片来显示。 //放大缩小图片 public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){ int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidht = ((float)w / width); float scaleHeight = ((float)h / height); matrix.postScale(scaleWidht, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newbmp; } //将Drawable转化为Bitmap public static Bitmap drawableToBitmap(Drawable drawable){ int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0,0,width,height); drawable.draw(canvas); return bitmap; Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. } //获得圆角图片的方法 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){ Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap .getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } //获得带倒影的图片方法 public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){ final int reflectionGap = 4; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height/2, width, height/2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. canvas.drawRect(0, height,width,height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值