Android位图Bitmap学习

Android图片缓存之Bitmap详解
Android图片之Bitmap
本文抄自第二篇,供学习使用。

1.Bitmap类

Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。

public void recycle() // 回收位图占用的内存空间,把位图标记为Dead
public final boolean isRecycled() //判断位图内存是否已释放  
public final int getWidth()//获取位图的宽度 
public final int getHeight()//获取位图的高度
public final boolean isMutable()//图片是否可修改 
public int getScaledWidth(Canvas canvas)//获取指定密度转换后的图像的宽度 
public int getScaledHeight(Canvas canvas)//获取指定密度转换后的图像的高度 

public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的图片格式以及画质,将图片转换为输出流。 
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。

public static Bitmap createBitmap(Bitmap src) //以src为原图生成不可变得新图像 
public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src为原图,创建新的图像,指定新图像的高宽以及是否可变。 
public static Bitmap createBitmap(int width, int height, Config config)——创建指定格式、大小的位图 
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source为原图,创建新的图片,指定起始坐标以及新图像的高宽。
2.BitmapFactory工厂类

Option 参数类:

public boolean inJustDecodeBounds//如果设置为true,不获取图片,不分配内存,但会返回图片的高度宽度信息。
public int inSampleSize//图片缩放的倍数
public int outWidth//获取图片的宽度值
public int outHeight//获取图片的高度值 
public int inDensity//用于位图的像素压缩比 
public int inTargetDensity//用于目标位图的像素压缩比(要生成的位图) 
public byte[] inTempStorage //创建临时文件,将图片存储
public boolean inScaled//设置为true时进行图片压缩,从inDensity到inTargetDensity
public boolean inDither //如果为true,解码器尝试抖动解码
public Bitmap.Config inPreferredConfig //设置解码器
public String outMimeType //设置解码图像
public boolean inPurgeable//当存储Pixel的内存空间在系统内存不足时是否可以被回收
public boolean inInputShareable //inPurgeable为true情况下才生效,是否可以共享一个InputStream
public boolean inPreferQualityOverSpeed  //为true则优先保证Bitmap质量其次是解码速度
public boolean inMutable //配置Bitmap是否可以更改,比如:在Bitmap上隔几个像素加一条线段
public int inScreenDensity //当前屏幕的像素密度

工厂方法:

public static Bitmap decodeFile(String pathName, Options opts) //从文件读取图片 
public static Bitmap decodeFile(String pathName)
public static Bitmap decodeStream(InputStream is) //从输入流读取图片
public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)
public static Bitmap decodeResource(Resources res, int id) //从资源文件读取图片
public static Bitmap decodeResource(Resources res, int id, Options opts) 
public static Bitmap decodeByteArray(byte[] data, int offset, int length) //从数组读取图片
public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
public static Bitmap decodeFileDescriptor(FileDescriptor fd)//从文件读取文件 与decodeFile不同的是这个直接调用JNI函数进行读取 效率比较高
public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)

Bitmap.Config inPreferredConfig :
枚举变量 (位图位数越高代表其可以存储的颜色信息越多,图像越逼真,占用内存越大)

public static final Bitmap.Config ALPHA_8 //代表8位Alpha位图        每个像素占用1byte内存
public static final Bitmap.Config ARGB_4444 //代表16位ARGB位图  每个像素占用2byte内存
public static final Bitmap.Config ARGB_8888 //代表32位ARGB位图  每个像素占用4byte内存
public static final Bitmap.Config RGB_565 //代表8位RGB位图          每个像素占用2byte内存

Android中一张图片(BitMap)占用的内存主要和以下几个因数有关:图片长度,图片宽度,单位像素占用的字节数。一张图片(BitMap)占用的内存=图片长度图片宽度单位像素占用的字节数

3.图片操作
3.1 获取图片的长宽

利用BitmapFactory.decodeXXX的Options参数
options.inJustDecodeBounds
options.outWidth / options.outWidth

File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "1.jpg");
//====获取图片的原始大小=====
BitmapFactory.Options options = new BitmapFactory.Options();
//如果设置为true,不获取图片,不分配内存,但会返回图片的高度宽度信息。
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
float srcWidth = options.outWidth;//获取图片的宽度值
float srcHeight =options.outHeight;//获取图片的高度值
3.2 对图片进行缩放(知道原来的长宽和目标的长宽进行的缩放)

利用BitmapFactory.decodeXXX的Options参数
options.inSampleSize

File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "haha.jpg");

//1 获取图片的原始大小
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//如果设置为true,不获取图片,不分配内存,但会返回图片的高度宽度信息。
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
float srcWidth = options.outWidth;//获取图片的宽度值
float srcHeight = options.outHeight;//获取图片的高度值

//2 得到目标显示的大小
int width = 300;//目标显示的长
int height = 300;//目标显示的宽

 //3 得到缩放比例
int inSampleSize = 1;
if (srcHeight > height || srcWidth > width) {
if (srcWidth > srcHeight) {
        inSampleSize = Math.round(srcWidth / width);
       } else {
               inSampleSize = Math.round(srcHeight / height);
       }
 }

//4 进行缩放
options.inJustDecodeBounds = false;
 options.inSampleSize = inSampleSize;

Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
iv.setImageBitmap(bitmap);
3.3 压缩图片(画质压缩)
public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的图片格式以及画质,将图片转换为输出流。 
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。

代码实现

InputStream is = getAssets().open("haha.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(is);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bytes = baos.toByteArray();
Bitmap bitmap1 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ivShow.setImageBitmap(bitmap1);
3.4 图片的缩放旋转等变形操作matrix(对长宽的操作,直接知道缩放比例)
InputStream is = getAssets().open("haha.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(is);

Matrix matrix = new Matrix();
matrix.postScale(4.0f, 4.0f);
matrix.postRotate(45f);
Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ivShow.setImageBitmap(bitmap1);
4.其他资源形式转为Bitmap
4.1 从文件获取图片显示

利用BitmapFactory的方法Bitmap decodeFile()或者Bitmap decodeFileDescriptor()
区别是是decodeFileDescriptor直接调用JNI函数进行读取,效率比较高,则建议优先使用第二种。

  • 方法一:使用Bitmap decodeFile()
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "haha.jpg");

BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 iv.setImageBitmap(bitmap);
  • 方法二:使用Bitmap decodeFileDescriptor()
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "haha.jpg");

FileInputStream fis = new FileInputStream(file);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);
iv.setImageBitmap(bitmap);
4.2 从输入流中获取图片显示
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "haha.jpg");

FileInputStream fis = new FileInputStream(file);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(fis,null,options);
iv.setImageBitmap(bitmap);
4.3 从资源文件中获取图片显示
BitmapFactory.Options options = new BitmapFactory.Options();
Resources resources = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.haha, options);
iv.setImageBitmap(bitmap);

此种方式相当的耗费内存,建议采用decodeStream代替decodeResource
BitmapFactory.decodeResource 加载的图片可能会经过缩放,该缩放目前是放在 java 层做的,效率比较低,而且需要消耗 java 层的内存。因此,如果大量使用该接口加载图片,容易导致OOM错误
BitmapFactory.decodeStream 不会对所加载的图片进行缩放,相比之下占用内存少,效率更高。

这两个接口各有用处,如果对性能要求较高,则应该使用 decodeStream;如果对性能要求不高,且需要 Android 自带的图片自适应缩放功能,则可以使用 decodeResource。

@SuppressLint("ResourceType")
InputStream inputStream = getResources().openRawResource(R.drawable.haha);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
iv.setImageBitmap(bitmap);
4.4 从二进制数据/字符串/字节数字中读取图片
byte[] bytes = baos.toByteArray();

Bitmap bitmap1 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
iv.setImageBitmap(bitmap1);
4.5 从assets文件中读取图片
InputStream is = getAssets().open("haha.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(is);
ivShow.setImageBitmap(bitmap);
is.close();
4.6 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);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
5.处理Bitmap图片成为其他资源形式
5.1 将Bitmap变成流
BufferedOutputStream baos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
5.2 将Bitmap存为文件
InputStream is = getAssets().open("haha.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(is);

File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "new.jpg");
BufferedOutputStream baos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
5.3 将Bitmap转为字符串/字节(存和取的时候建议用Base64再次编码,防止乱码)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] bytes = baos.toByteArray();
5.4 Bitmap转Drawable
InputStream inputStream = getAssets().open("haha.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Drawable drawable = new BitmapDrawable(getResources(), bitmap);

你可能感兴趣的:(android入门笔记)