com.bumptech.glide.util.Util Java Examples

The following examples show how to use com.bumptech.glide.util.Util. 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: GenericRequestBuilder.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Set the target the resource will be loaded into.
 *
 * @see Glide#clear(Target)
 *
 * @param target The target to load the resource into.
 * @return The given target.
 */
public <Y extends Target<TranscodeType>> Y into(Y target) {
    Util.assertMainThread();
    if (target == null) {
        throw new IllegalArgumentException("You must pass in a non null Target");
    }
    if (!isModelSet) {
        throw new IllegalArgumentException("You must first set a model (try #load())");
    }

    Request previous = target.getRequest();

    if (previous != null) {
        previous.clear();
        requestTracker.removeRequest(previous);
        previous.recycle();
    }

    Request request = buildRequest(target);
    target.setRequest(request);
    lifecycle.addListener(target);
    requestTracker.runRequest(request);

    return target;
}
 
Example #2
Source File: SizeStrategy.java    From giffun with Apache License 2.0 6 votes vote down vote up
@Override
public Bitmap get(int width, int height, Bitmap.Config config) {
    final int size = Util.getBitmapByteSize(width, height, config);
    Key key = keyPool.get(size);

    Integer possibleSize = sortedSizes.ceilingKey(size);
    if (possibleSize != null && possibleSize != size && possibleSize <= size * MAX_SIZE_MULTIPLE) {
        keyPool.offer(key);
        key = keyPool.get(possibleSize);
    }

    // Do a get even if we know we don't have a bitmap so that the key moves to the front in the lru pool
    final Bitmap result = groupedMap.get(key);
    if (result != null) {
        result.reconfigure(width, height, config);
        decrementBitmapOfSize(possibleSize);
    }

    return result;
}
 
Example #3
Source File: BitmapPreFillRunner.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to allocate {@link Bitmap}s and returns {@code true} if there are more
 * {@link Bitmap}s to allocate and {@code false} otherwise.
 */
private boolean allocate() {
    long start = clock.now();
    while (!toPrefill.isEmpty() && !isGcDetected(start)) {
        PreFillType toAllocate = toPrefill.remove();
        Bitmap bitmap = Bitmap.createBitmap(toAllocate.getWidth(), toAllocate.getHeight(),
                toAllocate.getConfig());

        // Don't over fill the memory cache to avoid evicting useful resources, but make sure it's not empty so
        // we use all available space.
        if (getFreeMemoryCacheBytes() >= Util.getBitmapByteSize(bitmap)) {
            memoryCache.put(new UniqueKey(), BitmapResource.obtain(bitmap, bitmapPool));
        } else {
            addToBitmapPool(toAllocate, bitmap);
        }

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "allocated [" + toAllocate.getWidth() + "x" + toAllocate.getHeight() + "] "
                    + toAllocate.getConfig() + " size: " + Util.getBitmapByteSize(bitmap));
        }
    }

    return !isCancelled && !toPrefill.isEmpty();
}
 
Example #4
Source File: BitmapTransformation.java    From giffun with Apache License 2.0 6 votes vote down vote up
@Override
public final Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) {
    if (!Util.isValidDimensions(outWidth, outHeight)) {
        throw new IllegalArgumentException("Cannot apply transformation on width: " + outWidth + " or height: "
                + outHeight + " less than or equal to zero and not Target.SIZE_ORIGINAL");
    }
    Bitmap toTransform = resource.get();
    int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
    int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
    Bitmap transformed = transform(bitmapPool, toTransform, targetWidth, targetHeight);

    final Resource<Bitmap> result;
    if (toTransform.equals(transformed)) {
        result = resource;
    } else {
        result = BitmapResource.obtain(transformed, bitmapPool);
    }

    return result;
}
 
Example #5
Source File: GenericRequestBuilder.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the {@link ImageView} the resource will be loaded into, cancels any existing loads into the view, and frees
 * any resources Glide may have previously loaded into the view so they may be reused.
 *
 * @see Glide#clear(android.view.View)
 *
 * @param view The view to cancel previous loads for and load the new resource into.
 * @return The {@link Target} used to wrap the given {@link ImageView}.
 */
public Target<TranscodeType> into(ImageView view) {
    Util.assertMainThread();
    if (view == null) {
        throw new IllegalArgumentException("You must pass in a non null View");
    }

    if (!isTransformationSet && view.getScaleType() != null) {
        switch (view.getScaleType()) {
            case CENTER_CROP:
                applyCenterCrop();
                break;
            case FIT_CENTER:
            case FIT_START:
            case FIT_END:
                applyFitCenter();
                break;
            //$CASES-OMITTED$
            default:
                // Do nothing.
        }
    }

    return into(glide.buildImageViewTarget(view, transcodeClass));
}
 
Example #6
Source File: BitmapTransformation.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public final Resource<Bitmap> transform(Context context, Resource<Bitmap> resource, int outWidth,
    int outHeight) {
  if (!Util.isValidDimensions(outWidth, outHeight)) {
    throw new IllegalArgumentException(
        "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight
            + " less than or equal to zero and not Target.SIZE_ORIGINAL");
  }
  BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
  Bitmap toTransform = resource.get();
  int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
  int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
  Bitmap transformed = transform(context.getApplicationContext(), bitmapPool, toTransform,
      targetWidth, targetHeight);

  final Resource<Bitmap> result;
  if (toTransform.equals(transformed)) {
    result = resource;
  } else {
    result = BitmapResource.obtain(transformed, bitmapPool);
  }
  return result;
}
 
Example #7
Source File: Glide4Loader.java    From ImageLoader with Apache License 2.0 6 votes vote down vote up
public String getSafeKey(Key key) {
    String safeKey;
    synchronized (loadIdToSafeHash) {
        safeKey = loadIdToSafeHash.get(key);
    }
    if (safeKey == null) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            key.updateDiskCacheKey(messageDigest);
            safeKey = Util.sha256BytesToHex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        synchronized (loadIdToSafeHash) {
            loadIdToSafeHash.put(key, safeKey);
        }
    }
    return safeKey;
}
 
Example #8
Source File: BitmapTransformation.java    From nativescript-image-cache-it with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public final Resource<Bitmap> transform(@NonNull Context context, @NonNull Resource<Bitmap> resource,
                                        int outWidth, int outHeight) {
    if (!Util.isValidDimensions(outWidth, outHeight)) {
        throw new IllegalArgumentException(
                "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight
                        + " less than or equal to zero and not Target.SIZE_ORIGINAL");
    }
    BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
    Bitmap toTransform = resource.get();
    System.out.println("target " + Target.SIZE_ORIGINAL + " outWidth " + outWidth  + " transform " +toTransform.getWidth()  );
    int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
    int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
    Bitmap transformed = transform(context.getApplicationContext(), bitmapPool, toTransform, targetWidth, targetHeight);

    final Resource<Bitmap> result;
    if (toTransform.equals(transformed)) {
        result = resource;
    } else {
        result = BitmapResource.obtain(transformed, bitmapPool);
    }
    return result;
}
 
Example #9
Source File: BitmapTransformation.java    From glide-transformations with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public final Resource<Bitmap> transform(@NonNull Context context, @NonNull Resource<Bitmap> resource,
                                        int outWidth, int outHeight) {
  if (!Util.isValidDimensions(outWidth, outHeight)) {
    throw new IllegalArgumentException(
        "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight
            + " less than or equal to zero and not Target.SIZE_ORIGINAL");
  }
  BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
  Bitmap toTransform = resource.get();
  int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
  int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
  Bitmap transformed = transform(context.getApplicationContext(), bitmapPool, toTransform, targetWidth, targetHeight);

  final Resource<Bitmap> result;
  if (toTransform.equals(transformed)) {
    result = resource;
  } else {
    result = BitmapResource.obtain(transformed, bitmapPool);
  }
  return result;
}
 
Example #10
Source File: GenericRequest.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void begin() {
    startTime = LogTime.getLogTime();
    if (model == null) {
        onException(null);
        return;
    }

    status = Status.WAITING_FOR_SIZE;
    if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
        onSizeReady(overrideWidth, overrideHeight);
    } else {
        target.getSize(this);
    }

    if (!isComplete() && !isFailed() && canNotifyStatusChanged()) {
        target.onLoadStarted(getPlaceholderDrawable());
    }
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logV("finished run method in " + LogTime.getElapsedMillis(startTime));
    }
}
 
Example #11
Source File: GenericRequest.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Cancels the current load if it is in progress, clears any resources held onto by the request and replaces
 * the loaded resource if the load completed with the placeholder.
 *
 * <p>
 *     Cleared requests can be restarted with a subsequent call to {@link #begin()}
 * </p>
 *
 * @see #cancel()
 */
@Override
public void clear() {
    Util.assertMainThread();
    if (status == Status.CLEARED) {
        return;
    }
    cancel();
    // Resource must be released before canNotifyStatusChanged is called.
    if (resource != null) {
        releaseResource(resource);
    }
    if (canNotifyStatusChanged()) {
        target.onLoadCleared(getPlaceholderDrawable());
    }
    // Must be after cancel().
    status = Status.CLEARED;
}
 
Example #12
Source File: RequestManagerRetriever.java    From giffun with Apache License 2.0 5 votes vote down vote up
public RequestManager get(FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        FragmentManager fm = activity.getSupportFragmentManager();
        return supportFragmentGet(activity, fm);
    }
}
 
Example #13
Source File: RequestManagerRetriever.java    From giffun with Apache License 2.0 5 votes vote down vote up
public RequestManager get(Fragment fragment) {
    if (fragment.getActivity() == null) {
        throw new IllegalArgumentException("You cannot start a load on a fragment before it is attached");
    }
    if (Util.isOnBackgroundThread()) {
        return get(fragment.getActivity().getApplicationContext());
    } else {
        FragmentManager fm = fragment.getChildFragmentManager();
        return supportFragmentGet(fragment.getActivity(), fm);
    }
}
 
Example #14
Source File: CustomTarget.java    From Simple-Dilbert with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@code CustomTarget} that will return the given {@code width} and {@link @code}
 * as the requested size (unless overridden by
 * {@link com.bumptech.glide.request.RequestOptions#override(int)} in the request).
 *
 * @param width  The requested width (>= 0, or == Target.SIZE_ORIGINAL).
 * @param height The requested height (>= 0, or == Target.SIZE_ORIGINAL).
 */
public CustomTarget(int width, int height) {
    if (!Util.isValidDimensions(width, height)) {
        throw new IllegalArgumentException(
                "Width and height must both be > 0 or Target#SIZE_ORIGINAL, but given" + " width: "
                        + width + " and height: " + height);
    }

    this.width = width;
    this.height = height;
}
 
Example #15
Source File: BitmapEncoder.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public boolean encode(Resource<Bitmap> resource, OutputStream os) {
    final Bitmap bitmap = resource.get();

    long start = LogTime.getLogTime();
    Bitmap.CompressFormat format = getFormat(bitmap);
    bitmap.compress(format, quality, os);
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Compressed with type: " + format + " of size " + Util.getBitmapByteSize(bitmap) + " in "
                + LogTime.getElapsedMillis(start));
    }
    return true;
}
 
Example #16
Source File: SizeConfigStrategy.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public void put(Bitmap bitmap) {
    int size = Util.getBitmapByteSize(bitmap);
    Key key = keyPool.get(size, bitmap.getConfig());

    groupedMap.put(key, bitmap);

    NavigableMap<Integer, Integer> sizes = getSizesForConfig(bitmap.getConfig());
    Integer current = sizes.get(key.size);
    sizes.put(key.size, current == null ? 1 : current + 1);
}
 
Example #17
Source File: SizeConfigStrategy.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public Bitmap get(int width, int height, Bitmap.Config config) {
    int size = Util.getBitmapByteSize(width, height, config);
    Key targetKey = keyPool.get(size, config);
    Key bestKey = findBestKey(targetKey, size, config);

    Bitmap result = groupedMap.get(bestKey);
    if (result != null) {
        // Decrement must be called before reconfigure.
        decrementBitmapOfSize(Util.getBitmapByteSize(result), result.getConfig());
        result.reconfigure(width, height,
                result.getConfig() != null ? result.getConfig() : Bitmap.Config.ARGB_8888);
    }
    return result;
}
 
Example #18
Source File: SizeConfigStrategy.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public Bitmap removeLast() {
    Bitmap removed = groupedMap.removeLast();
    if (removed != null) {
        int removedSize = Util.getBitmapByteSize(removed);
        decrementBitmapOfSize(removedSize, removed.getConfig());
    }
    return removed;
}
 
Example #19
Source File: SizeStrategy.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public void put(Bitmap bitmap) {
    int size = Util.getBitmapByteSize(bitmap);
    final Key key = keyPool.get(size);

    groupedMap.put(key, bitmap);

    Integer current = sortedSizes.get(key.size);
    sortedSizes.put(key.size, current == null ? 1 : current + 1);
}
 
Example #20
Source File: SizeStrategy.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public Bitmap removeLast() {
    Bitmap removed = groupedMap.removeLast();
    if (removed != null) {
        final int removedSize = Util.getBitmapByteSize(removed);
        decrementBitmapOfSize(removedSize);
    }
    return removed;
}
 
Example #21
Source File: ResourceRecycler.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void recycle(Resource<?> resource) {
    Util.assertMainThread();

    if (isRecycling) {
        // If a resource has sub-resources, releasing a sub resource can cause it's parent to be synchronously
        // evicted which leads to a recycle loop when the parent releases it's children. Posting breaks this loop.
        handler.obtainMessage(ResourceRecyclerCallback.RECYCLE_RESOURCE, resource).sendToTarget();
    } else {
        isRecycling = true;
        resource.recycle();
        isRecycling = false;
    }
}
 
Example #22
Source File: EngineJob.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void addCallback(ResourceCallback cb) {
    Util.assertMainThread();
    if (hasResource) {
        cb.onResourceReady(engineResource);
    } else if (hasException) {
        cb.onException(exception);
    } else {
        cbs.add(cb);
    }
}
 
Example #23
Source File: EngineJob.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void removeCallback(ResourceCallback cb) {
    Util.assertMainThread();
    if (hasResource || hasException) {
        addIgnoredCallback(cb);
    } else {
        cbs.remove(cb);
        if (cbs.isEmpty()) {
            cancel();
        }
    }
}
 
Example #24
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
public void release(Resource resource) {
    Util.assertMainThread();
    if (resource instanceof EngineResource) {
        ((EngineResource) resource).release();
    } else {
        throw new IllegalArgumentException("Cannot release anything but an EngineResource");
    }
}
 
Example #25
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void onEngineJobComplete(Key key, EngineResource<?> resource) {
    Util.assertMainThread();
    // A null resource indicates that the load failed, usually due to an exception.
    if (resource != null) {
        resource.setResourceListener(key, this);

        if (resource.isCacheable()) {
            activeResources.put(key, new ResourceWeakReference(key, resource, getReferenceQueue()));
        }
    }
    // TODO: should this check that the engine job is still current?
    jobs.remove(key);
}
 
Example #26
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public void onEngineJobCancelled(EngineJob engineJob, Key key) {
    Util.assertMainThread();
    EngineJob current = jobs.get(key);
    if (engineJob.equals(current)) {
        jobs.remove(key);
    }
}
 
Example #27
Source File: Engine.java    From giffun with Apache License 2.0 5 votes vote down vote up
@Override
public void onResourceReleased(Key cacheKey, EngineResource resource) {
    Util.assertMainThread();
    activeResources.remove(cacheKey);
    if (resource.isCacheable()) {
        cache.put(cacheKey, resource);
    } else {
        resourceRecycler.recycle(resource);
    }
}
 
Example #28
Source File: ListPreloader.java    From giffun with Apache License 2.0 5 votes vote down vote up
public PreloadTargetQueue(int size) {
    queue = Util.createQueue(size);

    for (int i = 0; i < size; i++) {
        queue.offer(new PreloadTarget());
    }
}
 
Example #29
Source File: VinylSimpleTarget.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void getSize(@NonNull SizeReadyCallback cb) {
    if (!Util.isValidDimensions(width, height)) {
        throw new IllegalArgumentException(
                "Width and height must both be > 0 or Target#SIZE_ORIGINAL, but given" + " width: "
                        + width + " and height: " + height + ", either provide dimensions in the constructor"
                        + " or call override()");
    }
    cb.onSizeReady(width, height);
}
 
Example #30
Source File: ApplicationIconDecoder.java    From glide-support with The Unlicense 5 votes vote down vote up
@Override public Resource<Drawable> decode(ApplicationInfo source, int width, int height) throws IOException {
	Drawable icon = context.getPackageManager().getApplicationIcon(source);
	return new DrawableResource<Drawable>(icon) {
		@Override public int getSize() { // best effort
			if (drawable instanceof BitmapDrawable) {
				return Util.getBitmapByteSize(((BitmapDrawable)drawable).getBitmap());
			} else {
				return 1;
			}
		}
		@Override public void recycle() { /* not from our pool */ }
	};
}