import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build; import com.example.android.common.logger.Log;
import com.example.android.displayingbitmaps.BuildConfig; import java.io.FileDescriptor; /**
* A simple subclass of {@link ImageWorker} that resizes images from resources given a target width
* and height. Useful for when the input images might be too large to simply load directly into
* memory.
*/
public class ImageResizer extends ImageWorker {
private static final String TAG = "ImageResizer";
protected int mImageWidth;
protected int mImageHeight; /**
* Initialize providing a single target image size (used for both width and height);
*
* @param context
* @param imageWidth
* @param imageHeight
*/
public ImageResizer(Context context, int imageWidth, int imageHeight) {
super(context);
setImageSize(imageWidth, imageHeight);
} /**
* Initialize providing a single target image size (used for both width and height);
*
* @param context
* @param imageSize
*/
public ImageResizer(Context context, int imageSize) {
super(context);
setImageSize(imageSize);
} /**
* Set the target image width and height.
*
* @param width
* @param height
*/
public void setImageSize(int width, int height) {
mImageWidth = width;
mImageHeight = height;
} /**
* Set the target image size (width and height will be the same).
*
* @param size
*/
public void setImageSize(int size) {
setImageSize(size, size);
} /**
* The main processing method. This happens in a background task. In this case we are just
* sampling down the bitmap and returning it from a resource.
*
* @param resId
* @return
*/
private Bitmap processBitmap(int resId) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "processBitmap - " + resId);
}
return decodeSampledBitmapFromResource(mResources, resId, mImageWidth,
mImageHeight, getImageCache());
} @Override
protected Bitmap processBitmap(Object data) {
return processBitmap(Integer.parseInt(String.valueOf(data)));
} /**
* Decode and sample down a bitmap from resources to the requested width and height.
*
* @param res The resources object containing the image data
* @param resId The resource id of the image data
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight, ImageCache cache) { // BEGIN_INCLUDE (read_bitmap_dimensions)
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// END_INCLUDE (read_bitmap_dimensions) // If we're running on Honeycomb or newer, try to use inBitmap
if (Utils.hasHoneycomb()) {
addInBitmapOptions(options, cache);
} // Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
} /**
* Decode and sample down a bitmap from a file to the requested width and height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight, ImageCache cache) { // First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options); // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // If we're running on Honeycomb or newer, try to use inBitmap
if (Utils.hasHoneycomb()) {
addInBitmapOptions(options, cache);
} // Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
} /**
* Decode and sample down a bitmap from a file input stream to the requested width and height.
*
* @param fileDescriptor The file descriptor to read from
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { // First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false; // If we're running on Honeycomb or newer, try to use inBitmap
if (Utils.hasHoneycomb()) {
addInBitmapOptions(options, cache);
} return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
} @TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // inBitmap only works with mutable bitmaps so force the decoder to
// return mutable bitmaps.
options.inMutable = true; if (cache != null) {
// Try and find a bitmap to use for inBitmap
Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) {
options.inBitmap = inBitmap;
}
} } /**
* Calculate an inSampleSize for use in a {@link android.graphics.BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link android.graphics.BitmapFactory}. This implementation calculates
* the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap
* having a width and height equal to or larger than the requested width and height.
*
* @param options An options object with out* params already populated (run through a decode*
* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// BEGIN_INCLUDE (calculate_sample_size)
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2;
final int 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;
} // This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize). long totalPixels = width * height / inSampleSize; // Anything more than 2x the requested pixels we'll sample down further
final long totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels > totalReqPixelsCap) {
inSampleSize *= 2;
totalPixels /= 2;
}
}
return inSampleSize;
// END_INCLUDE (calculate_sample_size)
}
}

DisplayingBitmaps.rar

Android ImageResizer:inSampleSize的更多相关文章

  1. Android异常:唤醒锁未授权。(Caused by: java.lang.SecurityException: Neither user 10044 nor current process has android.permission.WAKE_LOCK.)

    Android异常:Caused by: java.lang.SecurityException: Neither user 10044 nor current process has android ...

  2. android studio :com.android.support:appcompat-v7:21.+ 报错

    android studio :com.android.support:appcompat-v7:21.+ 报错: 在project——>app——>build.gradle修改: app ...

  3. Android开发:ScrollView嵌套GridView的解决办法

    Android开发:ScrollView嵌套GridView的解决办法   前些日子在开发中用到了需要ScrollView嵌套GridView的情况,由于这两款控件都自带滚动条,当他们碰到一起的时候便 ...

  4. Android入门:绑定本地服务

    一.绑定服务介绍   前面文章中讲过一般的通过startService开启的服务,当访问者关闭时,服务仍然存在: 但是如果存在这样一种情况:访问者需要与服务进行通信,则我们需要将访问者与服务进行绑定: ...

  5. Android 程式开发:(十三)特殊碎片 —— 13.2 DialogFragment

    Android 程式开发:(十三)特殊碎片 —— 13.2 DialogFragment 原文地址 我们也可以创建另外一种碎片——DialogFragment.顾名思义,DialogFragment就 ...

  6. Android基本功:Handler消息传送机制

    一.什么是UI线程 当程序第一次启动的时候,Android会同时启动一条主线程( Main Thread). 主要负责处理与UI相关的事件. 二.UI线程存在的问题 出于性能优化考虑,Android的 ...

  7. Android开发:最详细的 NavigationDrawer 开发实践总结

    最详细的 NavigationDrawer 开发实践总结 继前面写的两篇文章之后(有问题欢迎反馈哦): Android开发:Translucent System Bar 的最佳实践 Android开发 ...

  8. 【视频】零基础学Android开发:蓝牙聊天室APP(四)

    零基础学Android开发:蓝牙聊天室APP第四讲 4.1 ListView控件的使用 4.2 BaseAdapter具体解释 4.3 ListView分布与滚动事件 4.4 ListView事件监听 ...

  9. 【视频】零基础学Android开发:蓝牙聊天室APP(二)

    零基础学Android开发:蓝牙聊天室APP第二讲 2.1 课程内容应用场景 2.2 Android UI设计 2.3 组件布局:LinearLayout和RelativeLayout 2.4 Tex ...

随机推荐

  1. 经典SQL回顾之晋级篇

    上篇博文在说SQL基础的时候,有一个地方有点误导大家,文中说到SQL 中的substring()和C#中的substring()相同,这有点歧义.基本原理虽然相同,但是有一点很不一样,就是C#中索引是 ...

  2. Hive shell 命令

    Hive shell 命令. 连接 hive shell 直接输入 hive 1.显示表 hive> show tables; OK test Time taken: 0.17 seconds, ...

  3. js学习系列之-----apply和call

    apply call 从字面意思就看出来,申请请,呼叫. 打个比方就是别人有什么功能,你向别人,申请 呼叫 一下,哥们拿你的功能用一下,而apply 和call就是实现这样的功能 apply 和cal ...

  4. AWS SDK for C++调用第三方S3 API

    这里介绍AWS SDK for C++ 1.0.x版本,比如下载: https://github.com/aws/aws-sdk-cpp/archive/1.0.164.tar.gz 环境:RHEL/ ...

  5. thinkphp 自动跟新时间

    看了很多文章和资料了,明白何为真传一句话了... 模板里: <input type="text" name="time" value="{:da ...

  6. C++泛型和算法

    看书的速度终于慢了下来,倒不是难于理解,而是需要理解的东西有点多. 先吐槽下C++Primer这本书,不少地方都是用抽象的语言进行介绍! 拜托,你这是介绍,不是总结! 像容器适配器那里: “本质上,适 ...

  7. bootstrap -- css -- 按钮

    本文中提到的按钮样式,适用于:<a>, <button>, 或 <input> 元素上 但最好在 <button> 元素上使用按钮 class,避免跨浏 ...

  8. GC浅析之三-性能调优经验总结

    性能调优经验总结 问题的出现: 在日常环境下,以某server 为例,该机器的每秒的访问量均值在368左右,最大访问量在913.对外提供服务的表现为每两三个小时就有秒级别的时间客户端请求超时,在访问量 ...

  9. Unity3d + PureMVC框架搭建

    0.流程:LoginView-SendNotification()---->LoginCommand--Execute()--->调用proxy中的函数操作模型数据--LoginProxy ...

  10. Phpcms v9专题分类增加模板设置的方法

    Phpcms v9专题设置里面,默认专题子分类是无模板设置的,本文教你通过官方论坛给出的教程实现专题分类增加模板设置.先来看看默认专题子分类设置界面: 修改后的的专题子分类设置界面多了模板设置: 修改 ...