前言
这是比较基础的知识,但网上很多博客写的比较模糊
正好开这个专栏,就顺便写一篇,系统整理下,方便新手copy
创建Bitmap,Bitmap压缩,Bitmap写出,获取ARGB像素
//获取Bitmap原始尺寸
//当inJustDecodeBounds为true时,只获取Bitmap尺寸到option中,不解码图像数据,decodeFile返回的对象也为null
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
//从文件创建Bitmap,并压缩图像
//当inJustDecodeBounds为false时,会根据option参数对图像进行压缩,decodeFile返回压缩后的Bitmap
options.inJustDecodeBounds = false;
//图片太大则压缩,否则保持不变
//inSampleSize表示图片变成Bitmap时,宽高的缩小比例
//一般Bitmap没必要放大,放大在绘制时通过Canvas来控制即可
float expectedWidth = 720F;
if (options.outWidth > expectedWidth)
options.inSampleSize = (int) Math.ceil(options.outWidth / expectedWidth);
else
options.inSampleSize = 1;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//读取Bitmap中包含的ARGB像素数据
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
//将Bitmap对应的图片数据,写入到OutputStream中,再将OutputStream写入文件即可保存图片
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
//回收Bitmap对象
//一般也可以不调用,GC会自动回收
bitmap.recycle();