Android Bitmap 基础学习
2016-05-12 16:33
309 查看
Android Bitmap 基础学习
Bitmap 继承自Object 实现了Parelable接口,我们可以通过bitmap获取图片的基本信息,也可以对图片进行一系列操作比如对图片进行剪切,旋转,缩放等,操作过的图片我们可以指定格式进行保存。
1.Bitmap的生成方式
我们可以通过BitmapFactory来生成Bitmap;通常我们可以调用以下方法生成Bitmap。BitmapFactory.decodeFile(String pathName);
BitmapFactory.decodeFile(String pathName, BitmapFactory.Options opts);
BitmapFactory.decodeResource(Resources res, int id);
BitmapFactory.decodeResource(Resources res, int id, BitmapFactory.Options opts);
BitmapFactory.decodeFile()方法可以将文件夹中的图片解码为bitmap对象,BitmapFactory.decodeResource()可以从图片资源中解码为bitmap对象。
String uri = Environment.getExternalStorageDirectory().getAbsolutePath() + "/5555.jpg"; BitmapFactory.Options options = new BitmapFactory.Options(); //BitmapFactory中的一个内部类Options提供相关选项进行设置。 options.inJustDecodeBounds = true; //inJustDecodeBounds设为true时,decodeFile(uri, options)方法会测量出bitmap对象的宽高等基本信息并保存至options.outWidth和options.outHeight中,bitmap对象并不会被加载也不会消耗内存,因此我们在要压缩一张图片的时候经常利用这个方法测量出图片的宽高信息再计算出合适的压缩比例。 mBitmap = BitmapFactory.decodeFile(uri, options); options.inSampleSize = sampleSize(options,200,200); //inSampleSize设置图片的缩放比例,这个参数需要是2的幂函数。 options.inJustDecodeBounds = false; //测量完图片的宽高后设为false options.inPreferredConfig = Bitmap.Config.ARGB_4444; //inPreferredConfig 通过设置此值可以用来降低内存消耗,默认为ARGB_8888: 每个像素4字节. 共32位。 // Alpha_8: 只保存透明度,共8位,1字节。 // ARGB_4444: 共16位,2字节。 // RGB_565:共16位,2字节。 //如果不需要透明度,可把默认值ARGB_8888改为RGB_565,节约一半内存。 mBitmap = BitmapFactory.decodeFile(uri, options); //将uri路径对应得图片按照options设置的格式解码为bitmap对象 mImageView.setImageBitmap(mBitmap); // 根据maxWidth, maxHeight计算最合适的inSampleSize public static int sampleSize(BitmapFactory.Options options, int maxWidth, int maxHeight) { // raw height and width of image int rawWidth = options.outWidth; int rawHeight = options.outHeight; // calculate best sample size int inSampleSize = 0; if (rawHeight > maxHeight || rawWidth > maxWidth) { float ratioWidth = (float) rawWidth / maxWidth; float ratioHeight = (float) rawHeight / maxHeight; inSampleSize = (int) Math.min(ratioHeight, ratioWidth); } inSampleSize = Math.max(1, inSampleSize); return inSampleSize; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories