android.graphics.BitmapFactory#Options ( )源码实例Demo

下面列出了android.graphics.BitmapFactory#Options ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: CameraBlur   文件: ImageUtils.java
public static int calculateInSampleSize(BitmapFactory.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 heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;

    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }

    return inSampleSize;
}
 
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;
}
 
源代码3 项目: DesignOverlay-Android   文件: ImageUtil.java
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

        // 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;
            }
        }

        return inSampleSize;
    }
 
源代码4 项目: reader   文件: CameraLauncher.java
/**
 * Return a scaled bitmap based on the target width and height
 *
 * @param imagePath
 * @return
 * @throws IOException 
 */
private Bitmap getScaledBitmap(String imageUrl) throws IOException {
    // If no new width or height were specified return the original bitmap
    if (this.targetWidth <= 0 && this.targetHeight <= 0) {
        return BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova));
    }

    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options);
    
    //CB-2292: WTF? Why is the width null?
    if(options.outWidth == 0 || options.outHeight == 0)
    {
        return null;
    }
    
    // determine the correct aspect ratio
    int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);

    // Load in the smallest bitmap possible that is closest to the size we want
    options.inJustDecodeBounds = false;
    options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
    Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options);
    if (unscaledBitmap == null) {
        return null;
    }

    return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}
 
源代码5 项目: ScaleSketchPadDemo   文件: BitmapUtils.java
public static Bitmap decodeSampledBitmapFromResource(String path,
                                                     int reqWidth, int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
}
 
源代码6 项目: odyssey   文件: InsertImageTask.java
@Override
protected ArtworkRequestModel doInBackground(ImageResponse... params) {
    ImageResponse response = params[0];

    if (response.image == null) {
        insertImage(response.model, null, response.localArtworkPath);
        return response.model;
    }

    // Rescale them if to big
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(response.image, 0, response.image.length, options);
    if ((options.outHeight > MAXIMUM_IMAGE_RESOLUTION || options.outWidth > MAXIMUM_IMAGE_RESOLUTION)) {
        // Calculate minimal scaling factor
        float factor = Math.min((float) MAXIMUM_IMAGE_RESOLUTION / (float) options.outHeight, (float) MAXIMUM_IMAGE_RESOLUTION / (float) options.outWidth);
        options.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeByteArray(response.image, 0, response.image.length, options);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        Bitmap.createScaledBitmap(bm, (int) (options.outWidth * factor), (int) (options.outHeight * factor), true)
                .compress(Bitmap.CompressFormat.JPEG, IMAGE_COMPRESSION_SETTING, byteStream);

        if (byteStream.size() <= MAXIMUM_IMAGE_SIZE) {
            insertImage(response.model, byteStream.toByteArray(), null);
        }
    } else {
        if (response.image.length <= MAXIMUM_IMAGE_SIZE) {
            insertImage(response.model, response.image, null);
        }
    }

    return response.model;
}
 
源代码7 项目: narrate-android   文件: ViewPhotoActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_photo);

    Bundle extras = getIntent().getExtras();

    if ( extras == null ) {
        finish();
        return;
    }

    Photo photo = extras.getParcelable("photo");
    LogUtil.log(ViewPhotoActivity.class.getSimpleName(), "Photo Path: " + photo.path);

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;

    mImage = BitmapFactory.decodeFile(photo.path, options);

    if ( mImage.getWidth() > 4096 || mImage.getHeight() > 4096 ) {
        float ratio = (float) mImage.getHeight() / (float) mImage.getWidth();
        int width = mImage.getWidth();
        int height = 0;

        if ( width > 4096 ) {
            width = 4096;
            height = Math.round(width * ratio);
        } else {
            height = 4096;
            width = Math.round(height / ratio);
        }

        mImage = Bitmap.createScaledBitmap(mImage, width, height, false);
    }


    mImageView.setImageBitmap(mImage);
    mAttacher = new PhotoViewAttacher(mImageView);
}
 
源代码8 项目: Jreader   文件: BookPageFactory.java
public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // 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;
        } */
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
        // 一定都不会大于等于目标的宽和高。
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

    }

    return inSampleSize;
}
 
源代码9 项目: AlbumCameraRecorder   文件: BitmapUtils.java
/**
 * 压缩Bitmap的大小
 *
 * @param imagePath     图片文件路径
 * @param requestWidth  压缩到想要的宽度
 * @param requestHeight 压缩到想要的高度
 * @return
 */
public static Bitmap decodeBitmapFromFile(String imagePath, int requestWidth, int requestHeight) {
    if (!TextUtils.isEmpty(imagePath)) {
        Log.i(TAG, "requestWidth: " + requestWidth);
        Log.i(TAG, "requestHeight: " + requestHeight);
        if (requestWidth <= 0 || requestHeight <= 0) {
            return BitmapFactory.decodeFile(imagePath);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//不加载图片到内存,仅获得图片宽高
        BitmapFactory.decodeFile(imagePath, options);
        Log.i(TAG, "original height: " + options.outHeight);
        Log.i(TAG, "original width: " + options.outWidth);
        if (options.outHeight == -1 || options.outWidth == -1) {
            try {
                ExifInterface exifInterface = new ExifInterface(imagePath);
                int height = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的高度
                int width = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的宽度
                Log.i(TAG, "exif height: " + height);
                Log.i(TAG, "exif width: " + width);
                options.outWidth = width;
                options.outHeight = height;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight); //计算获取新的采样率
        Log.i(TAG, "inSampleSize: " + options.inSampleSize);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(imagePath, options);

    } else {
        return null;
    }
}
 
源代码10 项目: Matisse-Kotlin   文件: FileUtils.java
public static String extSuffix(InputStream input) {
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, options);
        return options.outMimeType.replace("image/", ".");
    } catch (Exception e) {
        return ".jpg";
    }
}
 
源代码11 项目: libcommon   文件: BitmapHelper.java
/**
	 * ファイルからビットマップデータを読み込んで指定した幅・高さのBitmapとして返す
	 * @param filePath
	 * @param requestWidth
	 * @param requestHeight
	 * @return
	 */
	@Nullable
	public static Bitmap asBitmapStrictSize(
		final String filePath,
		final int requestWidth, final int requestHeight) {

		Bitmap bitmap = null;
		if (!TextUtils.isEmpty(filePath)) {
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;	// Bitmapを生成せずにサイズ等の情報だけを取得する
			BitmapFactory.decodeFile(filePath, options);
			// 一番近いサイズになるSamplingSizeを計算
			final int calcedSampleSize = calcSampleSize(options, requestWidth, requestHeight);
			// 2のベキ乗に丸める=MSBを取得
			final int inSampleSize = 1 << BitsHelper.MSB(calcedSampleSize);
			options.inSampleSize = inSampleSize;
//			options.inMutable = (inSampleSize != calcedSampleSize);	// サイズ変更する時はmutableにする
			options.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeFile(filePath, options);
			final int orientation = getOrientation(filePath);
			if ((inSampleSize != calcedSampleSize)
				|| (orientation != 0)
				|| (bitmap.getWidth() != requestWidth)
				|| (bitmap.getHeight() != requestHeight)) {

				final Bitmap newBitmap = scaleRotateBitmap(bitmap, requestWidth, requestHeight, orientation);
				bitmap.recycle();
				bitmap = newBitmap;
			}
		}
		return bitmap;
	}
 
源代码12 项目: DevUtils   文件: ImageUtils.java
/**
 * 获取 Bitmap
 * @param resId   resource identifier
 * @param options {@link BitmapFactory.Options}
 * @return {@link Bitmap}
 */
public static Bitmap decodeResource(@DrawableRes final int resId, final BitmapFactory.Options options) {
    try {
        return BitmapFactory.decodeResource(ResourceUtils.getResources(), resId, options);
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "decodeResource");
        return null;
    }
}
 
源代码13 项目: tysq-android   文件: JerryUrlDrawable.java
@SuppressWarnings("deprecation")
public JerryUrlDrawable(Context context) {
    this.mContext = context;

    defaultDrawable = context.getResources()
            .getDrawable(R.drawable.placeholder_loading);

    BitmapFactory.Options options = new BitmapFactory.Options();

    // 只获取其宽高
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(this.mContext.getResources(),
            R.drawable.placeholder_loading,
            options);

    this.w = options.outWidth;
    this.h = options.outHeight;

    int jerryWidth = JerryConfig.getJerryWidth();

    float realHeight = h / (w * 1.0f) * jerryWidth;

    defaultDrawable.setBounds(0, 0, jerryWidth, (int) realHeight);

    Rect rect = new Rect(0, 0, w, h);
    this.setBounds(rect);
}
 
源代码14 项目: WanAndroid   文件: BitmapUtil.java
private static int calculateInSampleSize(BitmapFactory.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;
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}
 
源代码15 项目: iBeebo   文件: ImageUtility.java
public static Bitmap readNormalPic(String filePath, int reqWidth, int reqHeight) {
    try {

        if (!FileManager.isExternalStorageMounted()) {
            return null;
        }

        if (TextUtils.isEmpty(filePath)) {
            return null;
        }

        if (!filePath.endsWith(".jpg") && !filePath.endsWith(".gif") && !filePath.endsWith(".png")) {
            filePath = filePath + ".jpg";
        }

        boolean fileExist = new File(filePath).exists();

        if (!fileExist && !SettingUtils.isEnablePic()) {
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        if (reqHeight > 0 && reqWidth > 0) {
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        }
        options.inJustDecodeBounds = false;
        options.inPurgeable = true;
        options.inInputShareable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        if (bitmap == null) {
            // this picture is broken,so delete it
            new File(filePath).delete();
            return null;
        }

        if (reqHeight > 0 && reqWidth > 0) {
            int[] size = calcResize(bitmap.getWidth(), bitmap.getHeight(), reqWidth, reqHeight);
            if (size[0] > 0 && size[1] > 0) {
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, size[0], size[1], true);
                if (scaledBitmap != bitmap) {
                    bitmap.recycle();
                    bitmap = scaledBitmap;
                }
            }
        }

        return bitmap;
    } catch (OutOfMemoryError ignored) {
        ignored.printStackTrace();
        return null;
    }
}
 
源代码16 项目: TurboLauncher   文件: BitmapRegionTileSource.java
public Bitmap decodeRegion(Rect wantRegion, BitmapFactory.Options options) {
    return mDecoder.decodeRegion(wantRegion, options);
}
 
源代码17 项目: Hentoid   文件: SkiaImageDecoder.java
@Override
@NonNull
public Bitmap decode(@NonNull final Context context, @NonNull final Uri uri) throws IOException, PackageManager.NameNotFoundException {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = bitmapConfig;
    // If that is not set, some PNGs are read with a ColorSpace of code "Unknown" (-1),
    // which makes resizing buggy (generates a black picture)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        options.inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB);

    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        try (InputStream input = context.getContentResolver().openInputStream(uri)) {
            if (input == null)
                throw new RuntimeException("Content resolver returned null stream. Unable to initialise with uri.");
            bitmap = BitmapFactory.decodeStream(input, null, options);
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }

    return bitmap;
}
 
源代码18 项目: volley   文件: BitmapDecoder.java
public static Bitmap bytes2Bitmap(byte[] data, Config config, int maxWidth, int maxHeight) {
    if (data == null) return null;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap = null;
    if (maxWidth == 0 && maxWidth == 0) {
        decodeOptions.inPreferredConfig = config;
        decodeOptions.inPurgeable = true;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(maxWidth, maxHeight, actualWidth, actualHeight);
        int desiredHeight = getResizedDimension(maxHeight, maxWidth, actualHeight, actualWidth);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inPurgeable = true;
        // TODO(ficus): Do we need this or is it okay since API 8 doesn't
        // support it?
        // decodeOptions.inPreferQualityOverSpeed =
        // PREFER_QUALITY_OVER_SPEED;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = null;
        try {
            tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        } catch (OutOfMemoryError e) {
            decodeOptions.inSampleSize++;
            tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        }

        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }
    return bitmap;
}
 
源代码19 项目: FireFiles   文件: ImageUtils.java
public static Bitmap getVideoThumbnail(String path, int mMaxWidth, int mMaxHeight){
    Bitmap.Config mDecodeConfig = Bitmap.Config.RGB_565;
    ImageView.ScaleType mScaleType = ImageView.ScaleType.CENTER_CROP;

    File bitmapFile = new File(path);
    Bitmap bitmap = null;

    if (!bitmapFile.exists() || !bitmapFile.isFile()) {
        return bitmap;
    }

    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    decodeOptions.inInputShareable = true;
    decodeOptions.inPurgeable = true;
    decodeOptions.inPreferredConfig = mDecodeConfig;
    if (mMaxWidth == 0 && mMaxHeight == 0) {

        bitmap = getVideoFrame(bitmapFile.getAbsolutePath());
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        //BitmapFactory.decodeFile(bitmapFile.getAbsolutePath(), decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
                actualWidth, actualHeight, mScaleType);
        int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
                actualHeight, actualWidth, mScaleType);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inSampleSize = ImageUtils.findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = getVideoFrame(bitmapFile.getAbsolutePath());
        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null
                && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth,
                    desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }
    return bitmap;
}
 
源代码20 项目: LB-Launcher   文件: BitmapRegionTileSource.java
Bitmap decodeRegion(Rect wantRegion, BitmapFactory.Options options);