android.graphics.BitmapRegionDecoder Java Examples

The following examples show how to use android.graphics.BitmapRegionDecoder. 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: ImageEditorModule.java    From react-native-image-editor with MIT License 6 votes vote down vote up
/**
 * Reads and crops the bitmap.
 * @param outOptions Bitmap options, useful to determine {@code outMimeType}.
 */
private Bitmap crop(BitmapFactory.Options outOptions) throws IOException {
  InputStream inputStream = openBitmapInputStream();
  // Effeciently crops image without loading full resolution into memory
  // https://developer.android.com/reference/android/graphics/BitmapRegionDecoder.html
  BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(inputStream, false);
  try {
    Rect rect = new Rect(mX, mY, mX + mWidth, mY + mHeight);
    return decoder.decodeRegion(rect, outOptions);
  } finally {
    if (inputStream != null) {
      inputStream.close();
    }
    decoder.recycle();
  }
}
 
Example #2
Source File: BigView.java    From long_picture_view with Apache License 2.0 6 votes vote down vote up
/**
 * 由使用者输入一张图片
 */
public void setImage(InputStream is) {
    //先读取原图片的信息   高,宽
    mOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, mOptions);
    mImageWidth = mOptions.outWidth;
    mImageHeight = mOptions.outHeight;
    //开启复用
    mOptions.inMutable = true;
    //设置格式成RGB_565
    mOptions.inPreferredConfig = Bitmap.Config.RGB_565;
    mOptions.inJustDecodeBounds = false;

    //创建一个区域解码器
    try {
        mDecoder = BitmapRegionDecoder.newInstance(is, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
    requestLayout();
}
 
Example #3
Source File: DecodeUtils.java    From medialibrary with Apache License 2.0 6 votes vote down vote up
public static BitmapRegionDecoder createBitmapRegionDecoder(
        ThreadPool.JobContext jc, byte[] bytes, int offset, int length,
        boolean shareable) {
    if (offset < 0 || length <= 0 || offset + length > bytes.length) {
        throw new IllegalArgumentException(String.format(
                "offset = %s, length = %s, bytes = %s",
                offset, length, bytes.length));
    }

    try {
        return BitmapRegionDecoder.newInstance(
                bytes, offset, length, shareable);
    } catch (Throwable t)  {
        Log.w(TAG, t);
        return null;
    }
}
 
Example #4
Source File: ImageMetadata.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
private Bitmap readBitmap (final int scalePercentage, final Rect cropRect) throws IOException {
	if (100 % scalePercentage != 0) throw new IllegalArgumentException("scalePercentage " + scalePercentage + " is not a int ratio.");
	final Options opts = new Options();
	opts.inPurgeable = true;
	opts.inInputShareable = true;
	opts.inSampleSize = 100 / scalePercentage;

	if (cropRect != null) {
		final BitmapRegionDecoder dec = BitmapRegionDecoder.newInstance(openFileDescriptor().getFileDescriptor(), true);
		try {
			return dec.decodeRegion(cropRect, opts);
		}
		finally {
			dec.recycle();
		}
	}

	return BitmapFactory.decodeFileDescriptor(openFileDescriptor().getFileDescriptor(), null, opts);
}
 
Example #5
Source File: AttachmentRegionDecoder.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD_MR1)
@Override
public Point init(Context context, Uri uri) throws Exception {
  Log.w(TAG, "Init!");
  if (!PartAuthority.isLocalUri(uri)) {
    passthrough = new SkiaImageRegionDecoder();
    return passthrough.init(context, uri);
  }

  MasterSecret masterSecret = KeyCachingService.getMasterSecret(context);

  if (masterSecret == null) {
    throw new IllegalStateException("No master secret available...");
  }

  InputStream inputStream = PartAuthority.getAttachmentStream(context, masterSecret, uri);

  this.bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
  inputStream.close();

  return new Point(bitmapRegionDecoder.getWidth(), bitmapRegionDecoder.getHeight());
}
 
Example #6
Source File: AttachmentRegionDecoder.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Point init(Context context, Uri uri) throws Exception {
  ALog.w(TAG, "Init!");
  if (!PartAuthority.isLocalUri(uri)) {
    passthrough = new SkiaImageRegionDecoder();
    return passthrough.init(context, uri);
  }

  MasterSecret masterSecret = accountContext.getMasterSecret();

  if (masterSecret == null) {
    throw new IllegalStateException("No master secret available...");
  }

  InputStream inputStream = PartAuthority.getAttachmentStream(context, masterSecret, uri);

  this.bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
  inputStream.close();

  return new Point(bitmapRegionDecoder.getWidth(), bitmapRegionDecoder.getHeight());
}
 
Example #7
Source File: BitmapRegionTileSource.java    From TurboLauncher with Apache License 2.0 5 votes vote down vote up
public static SimpleBitmapRegionDecoderWrapper newInstance(
        InputStream is, boolean isShareable) {
    try {
        BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(is, isShareable);
        if (d != null) {
            return new SimpleBitmapRegionDecoderWrapper(d);
        }
    } catch (IOException e) {
        Log.w("BitmapRegionTileSource", "getting decoder failed", e);
        return null;
    }
    return null;
}
 
Example #8
Source File: SkiaPooledImageRegionDecoder.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
private synchronized BitmapRegionDecoder getNextAvailable() {
    for (Map.Entry<BitmapRegionDecoder, Boolean> entry : decoders.entrySet()) {
        if (!entry.getValue()) {
            entry.setValue(true);
            return entry.getKey();
        }
    }
    return null;
}
 
Example #9
Source File: SkiaPooledImageRegionDecoder.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
/**
 * While there are decoders in the map, wait until each is available before acquiring,
 * recycling and removing it. After this is called, any call to {@link #acquire()} will
 * block forever, so this call should happen within a write lock, and all calls to
 * {@link #acquire()} should be made within a read lock so they cannot end up blocking on
 * the semaphore when it has no permits.
 */
private synchronized void recycle() {
    while (!decoders.isEmpty()) {
        BitmapRegionDecoder decoder = acquire();
        if (decoder != null) {
            decoder.recycle();
            decoders.remove(decoder);
        }
    }
}
 
Example #10
Source File: SkiaPooledImageRegionDecoder.java    From subsampling-scale-image-view with Apache License 2.0 5 votes vote down vote up
private synchronized BitmapRegionDecoder getNextAvailable() {
    for (Map.Entry<BitmapRegionDecoder, Boolean> entry : decoders.entrySet()) {
        if (!entry.getValue()) {
            entry.setValue(true);
            return entry.getKey();
        }
    }
    return null;
}
 
Example #11
Source File: SkiaPooledImageRegionDecoder.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
/**
 * Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
 * exists and acquire a decoder to load the requested region. There is no check whether the pool
 * currently has decoders, because it's guaranteed to have one decoder after {@link #init(Context, Uri)}
 * is called and be null once {@link #recycle()} is called. In practice the view can't call this
 * method until after {@link #init(Context, Uri)}, so there will be no blocking on an empty pool.
 */
@Override
@NonNull
public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
    debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName());
    if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) {
        lazyInit();
    }
    decoderLock.readLock().lock();
    try {
        if (decoderPool != null) {
            BitmapRegionDecoder decoder = decoderPool.acquire();
            try {
                // Decoder can't be null or recycled in practice
                if (decoder != null && !decoder.isRecycled()) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = sampleSize;
                    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);

                    Bitmap bitmap = decoder.decodeRegion(sRect, options);
                    if (bitmap == null) {
                        throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
                    }
                    return bitmap;
                }
            } finally {
                if (decoder != null) {
                    decoderPool.release(decoder);
                }
            }
        }
        throw new IllegalStateException("Cannot decode region after decoder has been recycled");
    } finally {
        decoderLock.readLock().unlock();
    }
}
 
Example #12
Source File: DecoderDrawable.java    From Dashchan with Apache License 2.0 5 votes vote down vote up
public DecoderDrawable(Bitmap scaledBitmap, FileHolder fileHolder) throws IOException {
	this.scaledBitmap = scaledBitmap;
	if (!fileHolder.isRegionDecoderSupported()) {
		throw new IOException("Decoder drawable is not supported");
	}
	decoder = BitmapRegionDecoder.newInstance(fileHolder.openInputStream(), false);
	rotation = fileHolder.getRotation();
	width = fileHolder.getImageWidth();
	height = fileHolder.getImageHeight();
}
 
Example #13
Source File: HugeImageRegionLoader.java    From PinchImageView with MIT License 5 votes vote down vote up
@Override
protected void onPostExecute(BitmapRegionDecoder result) {
    if (!mRecyled) {
        mDecoder = result;
        if (mDecoder != null) {
            mWidth = mDecoder.getWidth();
            mHeight = mDecoder.getHeight();
            dispatchInited();
        }
    }
}
 
Example #14
Source File: BitmapThread.java    From Piclice with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        BitmapWorker.save(
                context,
                scale,
                filename,
                slice,
                BitmapRegionDecoder.newInstance(path, false).decodeRegion(new Rect(0, height * slice, width, height * (slice + 1)), bitmapOptions)
        );
        BitmapWorker.checkParts(filename);
    } catch (IOException ignored) {}
}
 
Example #15
Source File: BitmapRegionTileSource.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
public static SimpleBitmapRegionDecoderWrapper newInstance(
        String pathName, boolean isShareable) {
    try {
        BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(pathName, isShareable);
        if (d != null) {
            return new SimpleBitmapRegionDecoderWrapper(d);
        }
    } catch (IOException e) {
        Log.w("BitmapRegionTileSource", "getting decoder failed for path " + pathName, e);
        return null;
    }
    return null;
}
 
Example #16
Source File: SkiaPooledImageRegionDecoder.java    From subsampling-scale-image-view with Apache License 2.0 5 votes vote down vote up
private synchronized boolean markAsUnused(BitmapRegionDecoder decoder) {
    for (Map.Entry<BitmapRegionDecoder, Boolean> entry : decoders.entrySet()) {
        if (decoder == entry.getKey()) {
            if (entry.getValue()) {
                entry.setValue(false);
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}
 
Example #17
Source File: AttachmentRegionDecoder.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Point init(Context context, Uri uri) throws Exception {
  Log.w(TAG, "Init!");
  if (!PartAuthority.isLocalUri(uri)) {
    passthrough = new SkiaImageRegionDecoder();
    return passthrough.init(context, uri);
  }

  InputStream inputStream = PartAuthority.getAttachmentStream(context, uri);

  this.bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
  inputStream.close();

  return new Point(bitmapRegionDecoder.getWidth(), bitmapRegionDecoder.getHeight());
}
 
Example #18
Source File: SkiaPooledImageRegionDecoder.java    From PdfViewPager with Apache License 2.0 5 votes vote down vote up
private synchronized boolean markAsUnused(BitmapRegionDecoder decoder) {
    for (Map.Entry<BitmapRegionDecoder, Boolean> entry : decoders.entrySet()) {
        if (decoder == entry.getKey()) {
            if (entry.getValue()) {
                entry.setValue(false);
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}
 
Example #19
Source File: SkiaPooledImageRegionDecoder.java    From PdfViewPager with Apache License 2.0 5 votes vote down vote up
private synchronized void recycle() {
    while (!decoders.isEmpty()) {
        BitmapRegionDecoder decoder = acquire();
        decoder.recycle();
        decoders.remove(decoder);
    }
}
 
Example #20
Source File: SkiaPooledImageRegionDecoder.java    From PdfViewPager with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
    debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName());
    if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) {
        lazyInit();
    }
    decoderLock.readLock().lock();
    try {
        if (decoderPool != null) {
            BitmapRegionDecoder decoder = decoderPool.acquire();
            try {
                // Decoder can't be null or recycled in practice
                if (decoder != null && !decoder.isRecycled()) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = sampleSize;
                    options.inPreferredConfig = bitmapConfig;
                    Bitmap bitmap = decoder.decodeRegion(sRect, options);
                    if (bitmap == null) {
                        throw new RuntimeException(
                                "null bitmap - image format may not be supported");
                    }
                    return bitmap;
                }
            } finally {
                if (decoder != null) {
                    decoderPool.release(decoder);
                }
            }
        }
        throw new IllegalStateException("Cannot decode region after decoder has been recycled");
    } finally {
        decoderLock.readLock().unlock();
    }
}
 
Example #21
Source File: SkiaPooledImageRegionDecoder.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
private synchronized boolean markAsUnused(BitmapRegionDecoder decoder) {
    for (Map.Entry<BitmapRegionDecoder, Boolean> entry : decoders.entrySet()) {
        if (decoder == entry.getKey()) {
            if (entry.getValue()) {
                entry.setValue(false);
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}
 
Example #22
Source File: BitmapRegionTileSource.java    From Trebuchet with GNU General Public License v3.0 5 votes vote down vote up
public static SimpleBitmapRegionDecoderWrapper newInstance(
        InputStream is, boolean isShareable) {
    try {
        BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(is, isShareable);
        if (d != null) {
            return new SimpleBitmapRegionDecoderWrapper(d);
        }
    } catch (IOException e) {
        Log.w("BitmapRegionTileSource", "getting decoder failed", e);
        return null;
    }
    return null;
}
 
Example #23
Source File: TileBitmapDrawable.java    From ByakuGallery with Apache License 2.0 5 votes vote down vote up
private TileBitmapDrawable(ImageView parentView, BitmapRegionDecoder decoder, Bitmap screenNail) {
    mParentView = new WeakReference<ImageView>(parentView);

    synchronized (decoder) {
        mRegionDecoder = decoder;
        mIntrinsicWidth = mRegionDecoder.getWidth();
        mIntrinsicHeight = mRegionDecoder.getHeight();
    }

    final DisplayMetrics metrics = new DisplayMetrics();
    getDisplayMetrics(parentView.getContext(), metrics);

    mTileSize = metrics.densityDpi >= DisplayMetrics.DENSITY_HIGH ? TILE_SIZE_DENSITY_HIGH : TILE_SIZE_DEFAULT;

    mScreenNail = screenNail;

    synchronized (sBitmapCacheLock) {
        if (sBitmapCache == null) {
            // The Tile can be reduced up to half of its size until the next level of tiles is displayed
            final int maxHorizontalTiles = (int) Math.ceil(2 * metrics.widthPixels / (float) mTileSize);
            final int maxVerticalTiles = (int) Math.ceil(2 * metrics.heightPixels / (float) mTileSize);

            // The shared cache will have the minimum required size to display all visible tiles
            // Here, we multiply by 4 because in ARGB_8888 config, each pixel is stored on 4 bytes
            final int cacheSize = 4 * maxHorizontalTiles * maxVerticalTiles * mTileSize * mTileSize;

            sBitmapCache = new BitmapLruCache(cacheSize);
        }
    }

    mDecoderWorker = new DecoderWorker(this, mRegionDecoder, mDecodeQueue);
    mDecoderWorker.start();
}
 
Example #24
Source File: SkiaPooledImageRegionDecoder.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
/**
 * Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
 * exists and acquire a decoder to load the requested region. There is no check whether the pool
 * currently has decoders, because it's guaranteed to have one decoder after {@link #init(Context, Uri)}
 * is called and be null once {@link #recycle()} is called. In practice the view can't call this
 * method until after {@link #init(Context, Uri)}, so there will be no blocking on an empty pool.
 */
@Override
public Bitmap decodeRegion(Rect sRect, int sampleSize) {
    debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName());
    if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) {
        lazyInit();
    }
    decoderLock.readLock().lock();
    try {
        if (decoderPool != null) {
            BitmapRegionDecoder decoder = decoderPool.acquire();
            try {
                // Decoder can't be null or recycled in practice
                if (decoder != null && !decoder.isRecycled()) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = sampleSize;
                    options.inPreferredConfig = bitmapConfig;
                    Bitmap bitmap = decoder.decodeRegion(sRect, options);
                    if (bitmap == null) {
                        throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
                    }
                    return bitmap;
                }
            } finally {
                if (decoder != null) {
                    decoderPool.release(decoder);
                }
            }
        }
        throw new IllegalStateException("Cannot decode region after decoder has been recycled");
    } finally {
        decoderLock.readLock().unlock();
    }
}
 
Example #25
Source File: BitmapRegionTileSource.java    From LB-Launcher with Apache License 2.0 5 votes vote down vote up
public static SimpleBitmapRegionDecoderWrapper newInstance(
        String pathName, boolean isShareable) {
    try {
        BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(pathName, isShareable);
        if (d != null) {
            return new SimpleBitmapRegionDecoderWrapper(d);
        }
    } catch (IOException e) {
        Log.w("BitmapRegionTileSource", "getting decoder failed for path " + pathName, e);
        return null;
    }
    return null;
}
 
Example #26
Source File: DecodeUtils.java    From medialibrary with Apache License 2.0 5 votes vote down vote up
public static BitmapRegionDecoder createBitmapRegionDecoder(
        ThreadPool.JobContext jc, InputStream is, boolean shareable) {
    try {
        return BitmapRegionDecoder.newInstance(is, shareable);
    } catch (Throwable t)  {
        // We often cancel the creating of bitmap region decoder,
        // so just log one line.
        Log.w(TAG, "requestCreateBitmapRegionDecoder: " + t);
        return null;
    }
}
 
Example #27
Source File: SkiaPooledImageRegionDecoder.java    From subsampling-scale-image-view with Apache License 2.0 5 votes vote down vote up
/**
 * Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
 * exists and acquire a decoder to load the requested region. There is no check whether the pool
 * currently has decoders, because it's guaranteed to have one decoder after {@link #init(Context, Uri)}
 * is called and be null once {@link #recycle()} is called. In practice the view can't call this
 * method until after {@link #init(Context, Uri)}, so there will be no blocking on an empty pool.
 */
@Override
@NonNull
public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
    debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName());
    if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) {
        lazyInit();
    }
    decoderLock.readLock().lock();
    try {
        if (decoderPool != null) {
            BitmapRegionDecoder decoder = decoderPool.acquire();
            try {
                // Decoder can't be null or recycled in practice
                if (decoder != null && !decoder.isRecycled()) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = sampleSize;
                    options.inPreferredConfig = bitmapConfig;
                    Bitmap bitmap = decoder.decodeRegion(sRect, options);
                    if (bitmap == null) {
                        throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
                    }
                    return bitmap;
                }
            } finally {
                if (decoder != null) {
                    decoderPool.release(decoder);
                }
            }
        }
        throw new IllegalStateException("Cannot decode region after decoder has been recycled");
    } finally {
        decoderLock.readLock().unlock();
    }
}
 
Example #28
Source File: DecodeUtils.java    From medialibrary with Apache License 2.0 5 votes vote down vote up
public static BitmapRegionDecoder createBitmapRegionDecoder(
        ThreadPool.JobContext jc, String filePath, boolean shareable) {
    try {
        return BitmapRegionDecoder.newInstance(filePath, shareable);
    } catch (Throwable t)  {
        Log.w(TAG, t);
        return null;
    }
}
 
Example #29
Source File: ImageRegionDecoder.java    From sketch with Apache License 2.0 5 votes vote down vote up
public ImageRegionDecoder(@NonNull String imageUri, @NonNull Point imageSize, @Nullable ImageType imageType,
                           int exifOrientation, @NonNull BitmapRegionDecoder regionDecoder) {
    this.imageUri = imageUri;
    this.imageSize = imageSize;
    this.imageType = imageType;
    this.exifOrientation = exifOrientation;
    this.regionDecoder = regionDecoder;
}
 
Example #30
Source File: CompatHelperBase.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static Bitmap loadBitmapRegion(Path path,int sampleSize,Rect regionRect) throws IOException
{
	BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = sampleSize;
    InputStream data = path.getFile().getInputStream();
	try
	{
		if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.GINGERBREAD_MR1)
		{
			BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(data, true);
			try
			{
				return decoder.decodeRegion(regionRect, options);
			}
			finally
			{
				decoder.recycle();
			}
		}
		else
			return BitmapFactory.decodeStream(data, null, options);
	}
	finally
	{
		data.close();
	}
}