Android Bitmap那些事之如何优化内存
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Android Bitmap那些事之如何优化内存,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4901字,纯文字阅读大概需要8分钟。
内容图文
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds =true; BitmapFactory.decodeResource(getResources(), R.id.myimage, options); int imageHeight = options.outHeight; int imageWidth = options.outWidth; String imageType = options.outMimeType;
public static int calculateInSampleSize( BitmapFactory.Options options,int reqWidth,int reqHeight){ // Raw height and width of image finalint height = options.outHeight; finalint width = options.outWidth; int inSampleSize =1; if(height > reqHeight || width > reqWidth){ finalint halfHeight = height /2; finalint halfWidth = width /2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while((halfHeight / inSampleSize)> reqHeight &&(halfWidth / inSampleSize)> reqWidth){ inSampleSize *=2; } } return inSampleSize; }
public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId, int reqWidth,int reqHeight){ // First decode with inJustDecodeBounds=true to check dimensions finalBitmapFactory.Options options =newBitmapFactory.Options(); options.inJustDecodeBounds =true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds =false; returnBitmapFactory.decodeResource(res, resId, options); }
/** * 对图片进行压缩,主要是为了解决控件显示过大图片占用内存造成OOM问题,一般压缩后的图片大小应该和用来展示它的控件大小相近. * * @param context 上下文 * @param resId 图片资源Id * @param reqWidth 期望压缩的宽度 * @param reqHeight 期望压缩的高度 * @return 压缩后的图片 */ public static Bitmap compressBitmapFromResourse(Context context, int resId, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); /* * 第一次解析时,inJustDecodeBounds设置为true, * 禁止为bitmap分配内存,虽然bitmap返回值为空,但可以获取图片大小 */ options.inJustDecodeBounds = true; BitmapFactory.decodeResource(context.getResources(), resId, options); final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } options.inSampleSize = inSampleSize; // 使用计算得到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(context.getResources(), resId, options); }
原文:http://blog.csdn.net/cwuhao/article/details/45148679
内容总结
以上是互联网集市为您收集整理的Android Bitmap那些事之如何优化内存全部内容,希望文章能够帮你解决Android Bitmap那些事之如何优化内存所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。