Android Bitmap.Options.inSampleSize应该如何工作?
初始代码为官方文件: 我已经开始四处搜索,发现图像的大小并不像下面的例子中所描述的那样:Android Bitmap.Options.inSampleSize应该如何工作?,android,image,bitmap,android-6.0-marshmallow,Android,Image,Bitmap,Android 6.0 Marshmallow,初始代码为官方文件: 我已经开始四处搜索,发现图像的大小并不像下面的例子中所描述的那样: 如果设置为值>1,则请求解码器对原始图像进行二次采样,返回较小的图像以节省内存。样本大小是任一维度中对应于解码位图中单个像素的像素数。例如,inSampleSize==4返回的图像的宽度/高度为原始图像的1/4,像素数为1/16。任何值我确信,为什么BitmapFactory有一个decodeResource()方法,背后有一个愿景。我还没有完全弄明白那是什么景象 无论如何,使用decodeResource
如果设置为值>1,则请求解码器对原始图像进行二次采样,返回较小的图像以节省内存。样本大小是任一维度中对应于解码位图中单个像素的像素数。例如,inSampleSize==4返回的图像的宽度/高度为原始图像的1/4,像素数为1/16。任何值我确信,为什么
BitmapFactory
有一个decodeResource()
方法,背后有一个愿景。我还没有完全弄明白那是什么景象
无论如何,使用decodeResource()
并不能消除您拥有的任何特定于密度的资源的密度转换。因此,如果您使用的是-hdpi
设备,并且您的drawable的最佳匹配版本是res/drawable mdpi/
,inSampleSize
和密度转换都将发生。坦率地说,我还没有花时间试图弄清楚它们是如何结合在一起的
我想,如果你打算使用decodesource()
,它应该用于与特定密度无关的东西:将它放在res/drawable nodpi/
中。但是,那只是我
我应该去哪里了解密度背后的魔力
一般来说?有和
特别是关于位图工厂
?我不知道有任何关于这方面的报道
为什么它会根据inJustDecodeBounds
给出不同的大小
没有线索,抱歉。您的资源可能位于特定于密度的目录中,因此也将考虑密度转换。如果您正在使用资源(本身有点奇怪,IMHO)处理
inSampleSize
,请将资源移动到drawable/no dpi/
或assets/
或与密度无关的内容。@Commonware您是对的。我的资源在res/drawable
中。我已经将它移动到了res/drawable nodpi
,没有,它工作得很好。我应该去哪里了解密度背后的魔力?为什么它会根据inJustDecodeBounds
给出不同的大小?我的意思是它不一致。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
Log.e(LOG_TAG, "orig img size " + options.outWidth + "x" +
options.outHeight);
// Calculate inSampleSize
// options.inJustDecodeBounds = false; // version 2
for (int i = 2; i<20; i*=2) {
options.inSampleSize = i;
Log.d(LOG_TAG, "inSampleSize: " + options.inSampleSize);
Bitmap b = BitmapFactory.decodeResource(res, resId, options);
Log.e(LOG_TAG, "img size "+options.outWidth+"x"+options.outHeight);
if (b != null) {
Log.e(LOG_TAG, "real img size " + b.getWidth() + "x" +
b.getHeight() + " byte count " + b.getByteCount());
b.recycle();
}
}
E/t: view size 1080x1776
E/t: orig img size 2448x3264
D/t: inSampleSize: 2
E/t: img size 1224x1632
D/t: inSampleSize: 4
E/t: img size 612x816
D/t: inSampleSize: 8
E/t: img size 306x408
D/t: inSampleSize: 16
E/t: img size 153x204
D/t: inSampleSize: 32
E/t: img size 228x306
E/t: real img size 228x306 byte count 279072
E/t: view size 1080x1776
E/t: orig img size 2448x3264
D/t: inSampleSize: 2
W/art: Throwing OutOfMemoryError "Failed to allocate a 71912460 byte allocation with 1048576 free bytes and 62MB until OOM"
D/t: inSampleSize: 4
E/t: img size 1836x2448
E/t: real img size 1836x2448 byte count 17978112
D/t: inSampleSize: 8
E/t: img size 918x1224
E/t: real img size 918x1224 byte count 4494528
D/t: inSampleSize: 16
E/t: img size 459x612
E/t: real img size 459x612 byte count 1123632
D/t: inSampleSize: 32
E/t: img size 228x306
E/t: real img size 228x306 byte count 279072