下面列出了怎么用android.graphics.BitmapFactory.Options的API类实例代码及写法,或者点击链接到github查看源代码。
protected Options prepareDecodingOptions(ImageSize imageSize, ImageDecodingInfo decodingInfo) {
ImageScaleType scaleType = decodingInfo.getImageScaleType();
int scale;
if (scaleType == ImageScaleType.NONE) {
scale = 1;
} else if (scaleType == ImageScaleType.NONE_SAFE) {
scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
} else {
ImageSize targetSize = decodingInfo.getTargetSize();
boolean powerOf2 = scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2;
scale = ImageSizeUtils.computeImageSampleSize(imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
}
if (scale > 1 && loggingEnabled) {
L.d(LOG_SUBSAMPLE_IMAGE, imageSize, imageSize.scaleDown(scale), scale, decodingInfo.getImageKey());
}
Options decodingOptions = decodingInfo.getDecodingOptions();
decodingOptions.inSampleSize = scale;
return decodingOptions;
}
protected Options prepareDecodingOptions(ImageSize imageSize, ImageDecodingInfo decodingInfo) {
ImageScaleType scaleType = decodingInfo.getImageScaleType();
int scale;
if (scaleType == ImageScaleType.NONE) {
scale = 1;
} else if (scaleType == ImageScaleType.NONE_SAFE) {
scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
} else {
ImageSize targetSize = decodingInfo.getTargetSize();
boolean powerOf2 = scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2;
scale = ImageSizeUtils.computeImageSampleSize(imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
}
if (scale > 1 && loggingEnabled) {
L.d(LOG_SUBSAMPLE_IMAGE, imageSize, imageSize.scaleDown(scale), scale, decodingInfo.getImageKey());
}
Options decodingOptions = decodingInfo.getDecodingOptions();
decodingOptions.inSampleSize = scale;
return decodingOptions;
}
protected Options prepareDecodingOptions(ImageSize imageSize, ImageDecodingInfo decodingInfo) {
ImageScaleType scaleType = decodingInfo.getImageScaleType();
int scale;
if (scaleType == ImageScaleType.NONE) {
scale = 1;
} else if (scaleType == ImageScaleType.NONE_SAFE) {
scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
} else {
ImageSize targetSize = decodingInfo.getTargetSize();
boolean powerOf2 = scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2;
scale = ImageSizeUtils.computeImageSampleSize(imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
}
if (scale > 1 && loggingEnabled) {
L.d(LOG_SUBSAMPLE_IMAGE, imageSize, imageSize.scaleDown(scale), scale, decodingInfo.getImageKey());
}
Options decodingOptions = decodingInfo.getDecodingOptions();
decodingOptions.inSampleSize = scale;
return decodingOptions;
}
public FramesSequenceAnimation(ImageView imageView, int[] frames, int fps) {
this.mFrames = frames;
this.mIndex = -1;
this.mSoftReferenceImageView = new SoftReference(imageView);
this.mShouldRun = false;
this.mIsRunning = false;
this.mDelayMillis = 100;
imageView.setImageResource(this.mFrames[0]);
if (VERSION.SDK_INT >= 11) {
Bitmap bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
this.mBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
this.mBitmapOptions = new Options();
this.mBitmapOptions.inBitmap = this.mBitmap;
this.mBitmapOptions.inMutable = true;
this.mBitmapOptions.inSampleSize = 1;
this.mBitmapOptions.inPreferredConfig = Config.RGB_565;
}
}
/**
* Decodes image from URI into {@link android.graphics.Bitmap}. Image is scaled close to incoming {@linkplain com.nostra13.universalimageloader.core.assist.ImageSize target size}
* during decoding (depend on incoming parameters).
*
* @param decodingInfo Needed data for decoding image
* @return Decoded bitmap
* @throws java.io.IOException if some I/O exception occurs during image reading
* @throws UnsupportedOperationException if image URI has unsupported scheme(protocol)
*/
@Override
public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException {
Bitmap decodedBitmap;
ImageFileInfo imageInfo;
InputStream imageStream = getImageStream(decodingInfo);
try {
imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
imageStream = resetStream(imageStream, decodingInfo);
Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo);
decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions);
} finally {
IoUtils.closeSilently(imageStream);
}
if (decodedBitmap == null) {
L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey());
} else {
decodedBitmap = considerExactScaleAndOrientatiton(decodedBitmap, decodingInfo, imageInfo.exif.rotation,
imageInfo.exif.flipHorizontal);
}
return decodedBitmap;
}
/**
* 计算缩放比例
*
* @param opts
* @param reqWidth
* @param reqHeight
* @return
*/
private static int calculateInSampleSize(Options opts, int reqWidth,
int reqHeight) {
if (opts == null) return 1;
int inSampleSize = 1;
int realWidth = opts.outWidth;
int realHeight = opts.outHeight;
if (realHeight > reqHeight || realWidth > reqWidth) {
int widthRatio = realWidth / reqWidth;
int heightRatio = realHeight / reqHeight;
inSampleSize = (heightRatio > widthRatio) ? widthRatio : heightRatio;
}
return inSampleSize;
}
public ImageDecodingInfo(String imageKey, String imageUri, String originalImageUri, ImageSize targetSize, ViewScaleType viewScaleType,
ImageDownloader downloader, DisplayImageOptions displayOptions) {
this.imageKey = imageKey;
this.imageUri = imageUri;
this.originalImageUri = originalImageUri;
this.targetSize = targetSize;
this.imageScaleType = displayOptions.getImageScaleType();
this.viewScaleType = viewScaleType;
this.downloader = downloader;
this.extraForDownloader = displayOptions.getExtraForDownloader();
considerExifParams = displayOptions.isConsiderExifParams();
decodingOptions = new Options();
copyOptions(displayOptions.getDecodingOptions(), decodingOptions);
}
public ImageDecodingInfo(String imageKey, String imageUri, String originalImageUri, ImageSize targetSize, ViewScaleType viewScaleType,
ImageDownloader downloader, DisplayImageOptions displayOptions) {
this.imageKey = imageKey;
this.imageUri = imageUri;
this.originalImageUri = originalImageUri;
this.targetSize = targetSize;
this.imageScaleType = displayOptions.getImageScaleType();
this.viewScaleType = viewScaleType;
this.downloader = downloader;
this.extraForDownloader = displayOptions.getExtraForDownloader();
considerExifParams = displayOptions.isConsiderExifParams();
decodingOptions = new Options();
copyOptions(displayOptions.getDecodingOptions(), decodingOptions);
}
public NikonGetLiveViewImageCommand(NikonCamera camera, LiveViewData data) {
super(camera);
this.data = data;
if (data == null) {
this.data = new LiveViewData();
//this.data.histogram = ByteBuffer.allocate(1024 * 4);
//this.data.histogram.order(ByteOrder.LITTLE_ENDIAN);
} else {
this.data = data;
}
options = new BitmapFactory.Options();
options.inBitmap = this.data.bitmap;
options.inSampleSize = 1;
options.inTempStorage = tmpStorage;
this.data.bitmap = null;
}
public Builder() {
this.imageResOnLoading = 0;
this.imageResForEmptyUri = 0;
this.imageResOnFail = 0;
this.imageOnLoading = null;
this.imageForEmptyUri = null;
this.imageOnFail = null;
this.resetViewBeforeLoading = false;
this.cacheInMemory = false;
this.cacheOnDisk = false;
this.imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;
this.decodingOptions = new Options();
this.delayBeforeLoading = 0;
this.considerExifParams = false;
this.extraForDownloader = null;
this.preProcessor = null;
this.postProcessor = null;
this.displayer = DefaultConfigurationFactory.createBitmapDisplayer();
this.handler = null;
this.isSyncLoading = false;
this.decodingOptions.inPurgeable = true;
this.decodingOptions.inInputShareable = true;
}
private void copyOptions(Options srcOptions, Options destOptions) {
destOptions.inDensity = srcOptions.inDensity;
destOptions.inDither = srcOptions.inDither;
destOptions.inInputShareable = srcOptions.inInputShareable;
destOptions.inJustDecodeBounds = srcOptions.inJustDecodeBounds;
destOptions.inPreferredConfig = srcOptions.inPreferredConfig;
destOptions.inPurgeable = srcOptions.inPurgeable;
destOptions.inSampleSize = srcOptions.inSampleSize;
destOptions.inScaled = srcOptions.inScaled;
destOptions.inScreenDensity = srcOptions.inScreenDensity;
destOptions.inTargetDensity = srcOptions.inTargetDensity;
destOptions.inTempStorage = srcOptions.inTempStorage;
if (VERSION.SDK_INT >= 10) {
copyOptions10(srcOptions, destOptions);
}
if (VERSION.SDK_INT >= 11) {
copyOptions11(srcOptions, destOptions);
}
}
protected Options prepareDecodingOptions(ImageSize imageSize, ImageDecodingInfo decodingInfo) {
int scale;
ImageScaleType scaleType = decodingInfo.getImageScaleType();
if (scaleType == ImageScaleType.NONE) {
scale = 1;
} else if (scaleType == ImageScaleType.NONE_SAFE) {
scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
} else {
boolean powerOf2;
ImageSize targetSize = decodingInfo.getTargetSize();
if (scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2) {
powerOf2 = true;
} else {
powerOf2 = false;
}
scale = ImageSizeUtils.computeImageSampleSize(imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
}
if (scale > 1 && this.loggingEnabled) {
L.d(LOG_SUBSAMPLE_IMAGE, imageSize, imageSize.scaleDown(scale), Integer.valueOf(scale), decodingInfo.getImageKey());
}
Options decodingOptions = decodingInfo.getDecodingOptions();
decodingOptions.inSampleSize = scale;
return decodingOptions;
}
/**
* 计算文件大小
*
* @param options
* @param minSideLength
* @param maxNumOfPixels
* @return
*/
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
public static Bitmap getBitmapByPath(String filename) {
if (!checkFileIsEnabledPath(filename)) {
return null;
}
Options newOpts = new Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(filename, newOpts);
int w = newOpts.outWidth;
int h = newOpts.outHeight;
if (bitmap != null) {
bitmap.recycle();
}
int be = 1;
if (w > h && ((float) w) > 300.0f) {
be = (int) (((float) newOpts.outWidth) / 300.0f);
} else if (w < h && ((float) h) > 400.0f) {
be = (int) (((float) newOpts.outHeight) / 400.0f);
}
if (be <= 0) {
be = 1;
}
Options newOpts2 = new Options();
newOpts2.inSampleSize = be;
newOpts2.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, newOpts2);
}
private static int computeInitialSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
double w = (double) options.outWidth;
double h = (double) options.outHeight;
int lowerBound = maxNumOfPixels == -1 ? 1 : (int) Math.ceil(Math.sqrt((w * h) / ((double) maxNumOfPixels)));
int upperBound = minSideLength == -1 ? 128 : (int) Math.min(Math.floor(w / ((double) minSideLength)), Math.floor(h / ((double) minSideLength)));
if (upperBound < lowerBound) {
return lowerBound;
}
if (maxNumOfPixels == -1 && minSideLength == -1) {
return 1;
}
if (minSideLength != -1) {
return upperBound;
}
return lowerBound;
}
private static final boolean b(String str, int i, int i2) {
if (TextUtils.isEmpty(str)) {
return false;
}
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(str, options);
int i3 = options.outWidth;
int i4 = options.outHeight;
if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) {
return false;
}
int i5 = i3 > i4 ? i3 : i4;
if (i3 >= i4) {
i3 = i4;
}
f.b("AsynScaleCompressImage", "longSide=" + i5 + "shortSide=" + i3);
options.inPreferredConfig = Config.RGB_565;
if (i5 > i2 || i3 > i) {
return true;
}
return false;
}
private static int b(Options options, int i, int i2) {
double d = (double) options.outWidth;
double d2 = (double) options.outHeight;
int ceil = i2 == -1 ? 1 : (int) Math.ceil(Math.sqrt((d * d2) / ((double) i2)));
int min = i == -1 ? 128 : (int) Math.min(Math.floor(d / ((double) i)), Math.floor(d2 / ((double) i)));
if (min < ceil) {
return ceil;
}
if (i2 == -1 && i == -1) {
return 1;
}
if (i != -1) {
return min;
}
return ceil;
}
private Bitmap a(String str) throws IOException {
int i = 1;
Options options = new Options();
options.inJustDecodeBounds = true;
Uri parse = Uri.parse(str);
InputStream openInputStream = getContentResolver().openInputStream(parse);
if (openInputStream == null) {
return null;
}
BitmapFactory.decodeStream(openInputStream, null, options);
openInputStream.close();
int i2 = options.outWidth;
int i3 = options.outHeight;
while (i2 * i3 > 4194304) {
i2 /= 2;
i3 /= 2;
i *= 2;
}
options.inJustDecodeBounds = false;
options.inSampleSize = i;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(parse), null, options);
}
/**
* 计算文件大小
*
* @param options
* @param minSideLength
* @param maxNumOfPixels
* @return
*/
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
public static IconRequest build(Context context, String iconHash) {
if (iconHash == null) {
return null;
}
try {
int iconId = CommonUtils.getAppIconResourceId(context);
Fabric.getLogger().d(Fabric.TAG, "App icon resource ID is " + iconId);
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(context.getResources(), iconId, options);
return new IconRequest(iconHash, iconId, options.outWidth, options.outHeight);
} catch (Exception e) {
Fabric.getLogger().e(Fabric.TAG, "Failed to load icon", e);
return null;
}
}
public ImageDecodingInfo(String imageKey, String imageUri, String originalImageUri, ImageSize targetSize, ViewScaleType viewScaleType,
ImageDownloader downloader, DisplayImageOptions displayOptions) {
this.imageKey = imageKey;
this.imageUri = imageUri;
this.originalImageUri = originalImageUri;
this.targetSize = targetSize;
this.imageScaleType = displayOptions.getImageScaleType();
this.viewScaleType = viewScaleType;
this.downloader = downloader;
this.extraForDownloader = displayOptions.getExtraForDownloader();
considerExifParams = displayOptions.isConsiderExifParams();
decodingOptions = new Options();
copyOptions(displayOptions.getDecodingOptions(), decodingOptions);
}
public static int computeSampleSize(Options options, int target) {
int w = options.outWidth;
int h = options.outHeight;
int candidateW = w / target;
int candidateH = h / target;
int candidate = Math.max(candidateW, candidateH);
if (candidate == 0) {
return 1;
}
if (candidate > 1) {
if ((w > target) && (w / candidate) < target) {
candidate -= 1;
}
}
if (candidate > 1) {
if ((h > target) && (h / candidate) < target) {
candidate -= 1;
}
}
return candidate;
}
private Bitmap getResBitmap(int bmpResId) {
Options opts = new Options();
opts.inDither = false;
Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, bmpResId, opts);
if (bmp == null && isInEditMode()) {
// BitmapFactory.decodeResource doesn't work from the rendering
// library in Eclipse's Graphical Layout Editor. Use this workaround instead.
Drawable d = res.getDrawable(bmpResId);
int w = d.getIntrinsicWidth();
int h = d.getIntrinsicHeight();
bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas c = new Canvas(bmp);
d.setBounds(0, 0, w - 1, h - 1);
d.draw(c);
}
return bmp;
}
private EmojiUtil(Context context) {
this.context = context;
density = context.getResources().getDisplayMetrics().density;
try {
if (density >= 1.5f) {
this.isHdpi = true;
InputStream localInputStream = context.getAssets().open("emoji/emoji_2x.png");
Options opts = new Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
emojiImages = BitmapFactory.decodeStream(localInputStream, null, opts);
}
String[] index = EMOJI_INDEX.split("\n");
emojiRects = new HashMap<String, Rect>();
emojiDrawables = new HashMap<String, SoftReference<Drawable>>();
for (int i = 0; i < index.length; i++) {
String[] emojis = index[i].split("-");
for (int j = 0; j < emojis.length; j++) {
emojiRects.put(emojis[j], new Rect(j * 40, i * 40, 40 * (j + 1), 40 * (i + 1)));
}
}
} catch (IOException localIOException) {
}
}
/**
* 获取图片缩略�? 只有Android2.1以上版本支持
*
* @param imgName
* @param kind MediaStore.Images.Thumbnails.MICRO_KIND
* @return
*/
@SuppressWarnings("deprecation")
public static Bitmap loadImgThumbnail(Activity context, String imgName,
int kind) {
Bitmap bitmap = null;
String[] proj = {MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = context.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'",
null, null);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
ContentResolver crThumb = context.getContentResolver();
Options options = new Options();
options.inSampleSize = 1;
bitmap = getThumbnail(crThumb, cursor.getInt(0),
kind, options);
}
return bitmap;
}
/**
* 创建缩略�?
*
* @param context
* @param largeImagePath 原始大图路径
* @param thumbfilePath 输出缩略图路�?
* @param square_size 输出图片宽度
* @param quality 输出图片质量
* @throws IOException
*/
public static void createImageThumbnail(Context context, String largeImagePath, String thumbfilePath, int square_size, int quality) throws IOException {
Options opts = new Options();
opts.inSampleSize = 1;
// 原始图片bitmap
Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
if (cur_bitmap == null)
throw new IOException();
// 原始图片的高�?
int[] cur_img_size = new int[]{cur_bitmap.getWidth(),
cur_bitmap.getHeight()};
// 计算原始图片缩放后的宽高
int[] new_img_size = scaleImageSize(cur_img_size, square_size);
// 生成缩放后的bitmap
Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
new_img_size[1]);
// 生成缩放后的图片文件
saveImageToSD(context, thumbfilePath, thb_bitmap, quality);
}
public static boolean isThisBitmapTooLargeToRead(String path) {
File file = new File(path);
if (!file.exists()) {
return false;
}
final Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int width = options.outWidth;
int height = options.outHeight;
if (width == -1 || height == -1) {
return false;
}
if (width > getBitmapMaxWidthAndMaxHeight()
|| height > getBitmapMaxWidthAndMaxHeight()) {
return true;
} else {
return false;
}
}
/**
* 根据需求的宽和高以及图片实际的宽和高计算SampleSize
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int caculateInSampleSize(Options options, int reqWidth,
int reqHeight)
{
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (width > reqWidth || height > reqHeight)
{
int widthRadio = Math.round(width * 1.0f / reqWidth);
int heightRadio = Math.round(height * 1.0f / reqHeight);
inSampleSize = Math.max(widthRadio, heightRadio);
}
return inSampleSize;
}
/**
* Calculates a proper value for options.inSampleSize in order to decode a Bitmap minimizing
* the memory overload and covering a target surface of reqWidth x reqHeight if the original
* image is big enough.
*
* @param options Bitmap decoding options; options.outHeight and options.inHeight should
* be set.
* @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
* @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
* @return The largest inSampleSize value that is a power of 2 and keeps both
* height and width larger than reqWidth and reqHeight.
*/
private static int calculateSampleFactor(Options options, int reqWidth, int reqHeight) {
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;
// calculates the largest inSampleSize value (for smallest sample) 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 SimulationView(Context context) {
super(context);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mXDpi = metrics.xdpi;
mYDpi = metrics.ydpi;
mMetersToPixelsX = mXDpi / 0.0254f;
mMetersToPixelsY = mYDpi / 0.0254f;
// rescale the ball so it's about 0.5 cm on screen
mDstWidth = (int) (sBallDiameter * mMetersToPixelsX + 0.5f);
mDstHeight = (int) (sBallDiameter * mMetersToPixelsY + 0.5f);
mParticleSystem = new ParticleSystem();
Options opts = new Options();
opts.inDither = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}