Sean's Note: About BitmapFactory.Option.inSampleSize

2013年8月16日 星期五

About BitmapFactory.Option.inSampleSize

本以為這個數字可以隨便設,後來看了一下官方寫的文件後才發現,

這個設定只有 2 的冪次方效果, 也就是圖片 down-sapling 完不會有 1/3 或 1/5

的效果。 因為設其他數值,底下也是會取接近 2 的冪次方來做運算。 

例如: 設 3,底層實際取 2 做運算;設 4, 5, 6, 7 ,實際皆取 4 做運算。

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. 
The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. 
For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. 
Any value <= 1 is treated the same as 1. 
Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.
資料來源: 官方網站

仔細看了一下 skia library 的原始檔 SkImageDecoder_libjpeg.cpp,發現 Android 也是

用 IJG 的 JPEG Lib 去做 down-sapling:

bool SkJPEGImageDecoder::onDecode(SkStream* stream, SkBitmap* bm, SkBitmap::Config prefConfig, Mode mode)
{
    ...
    jpeg_decompress_struct cinfo;
    cinfo.scale_denom = sampleSize;
    ...
}

Google 了一下 scale_denom 的說明,文件上也說明的相當清楚了。

unsigned int scale_num, scale_denom Scale the image by the fraction scale_num/scale_denom. Default is 1/1, or no scaling. 
Currently, the only supported scaling ratios are 1/1, 1/2, 1/4, and 1/8. (The library design allows for arbitrary scaling ratios but 
this is not likely to be implemented any time soon.) Smaller scaling ratios permit significantly faster decoding since fewer 
pixels need be processed and a simpler IDCT method can be used.
資料來源: 網站

沒有留言:

張貼留言