Java Code Examples for android.graphics.BitmapFactory#Options

The following examples show how to use android.graphics.BitmapFactory#Options . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtil.java    From DesignOverlay-Android with Apache License 2.0 6 votes vote down vote up
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;
    }
 
Example 2
Source File: NikonGetLiveViewImageCommand.java    From remoteyourcam-usb with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: ImageUtils.java    From CameraBlur with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: BitmapUtils.java    From ScaleSketchPadDemo with MIT License 5 votes vote down vote up
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);
}
 
Example 5
Source File: BitmapUtil.java    From WanAndroid with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: JerryUrlDrawable.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 7
Source File: ImageUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 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;
    }
}
 
Example 8
Source File: BitmapHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
	 * ファイルからビットマップデータを読み込んで指定した幅・高さの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;
	}
 
Example 9
Source File: FileUtils.java    From Matisse-Kotlin with Apache License 2.0 5 votes vote down vote up
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";
    }
}
 
Example 10
Source File: BitmapUtils.java    From AlbumCameraRecorder with MIT License 5 votes vote down vote up
/**
 * 压缩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;
    }
}
 
Example 11
Source File: BookPageFactory.java    From Jreader with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: ViewPhotoActivity.java    From narrate-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 13
Source File: InsertImageTask.java    From odyssey with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 14
Source File: CameraLauncher.java    From reader with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 15
Source File: BitmapRegionTileSource.java    From TurboLauncher with Apache License 2.0 4 votes vote down vote up
public Bitmap decodeRegion(Rect wantRegion, BitmapFactory.Options options) {
    return mDecoder.decodeRegion(wantRegion, options);
}
 
Example 16
Source File: SkiaImageDecoder.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 17
Source File: ImageUtility.java    From iBeebo with GNU General Public License v3.0 4 votes vote down vote up
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;
    }
}
 
Example 18
Source File: BitmapDecoder.java    From volley with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 19
Source File: ImageUtils.java    From FireFiles with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: BitmapRegionTileSource.java    From LB-Launcher with Apache License 2.0 votes vote down vote up
Bitmap decodeRegion(Rect wantRegion, BitmapFactory.Options options);