Java Code Examples for com.bumptech.glide.request.target.Target

The following examples show how to use com.bumptech.glide.request.target.Target. These examples are extracted from open source projects. 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 Project: Mysplash   Source File: ImageHelper.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void loadImage(Context context, ImageView view,
                             @NonNull String url, @Nullable String thumbUrl,
                             @Size(2) @Px int[] size, @Nullable @Size(2) @Px int[] thumbSize,
                             @Nullable BitmapTransformation[] ts, @Nullable OnLoadImageListener l) {
    if (thumbSize == null) {
        thumbSize = new int[] {Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL};
    }
    DrawableRequestBuilder<String> thumb = TextUtils.isEmpty(thumbUrl) ? null : Glide.with(getValidContext(context))
            .load(ensureUrl(thumbUrl))
            .override(thumbSize[0], thumbSize[1])
            .diskCacheStrategy(
                    thumbSize[0] == Target.SIZE_ORIGINAL
                            ? DiskCacheStrategy.NONE
                            : DiskCacheStrategy.SOURCE
            ).listener(
                    new BaseRequestListener<>(() -> view.setTag(R.id.tag_item_image_fade_in_flag, false))
            );
    loadImage(context, view, url, thumb, size, ts, l);
}
 
Example 2
Source Project: giffun   Source File: GenericRequestBuilder.java    License: 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 3
Source Project: glide-support   Source File: TestFragment.java    License: The Unlicense 6 votes vote down vote up
private void load(final ImageView imageView) {
	if (imageView.getHeight() == 0) {
		// wait for layout, same as glide SizeDeterminer does
		imageView.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
			@Override public boolean onPreDraw() {
				imageView.getViewTreeObserver().removeOnPreDrawListener(this);
				load(imageView); // call the same method, but we can be sure now getHeight() is a value
				return true;
			}
		});
	} else {
		Glide
				.with(imageView.getContext())
				.load("whatever")
				.fitCenter()
				.override(Target.SIZE_ORIGINAL, imageView.getHeight())
				.into(imageView);
	}
}
 
Example 4
Source Project: giffun   Source File: BitmapTransformation.java    License: 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 Project: music_player   Source File: PlayService.java    License: Open Software License 3.0 6 votes vote down vote up
private void updateMetaDataAndBuildNotification() {
    musicInfo musicNow = MyApplication.getMusicListNow().get(MyApplication.getPositionNow());
    singerNow = musicNow.getMusicArtist();
    titleNow = musicNow.getMusicTitle();
    if (!musicNow.getMusicLink().equals("")) {//网络
        Glide.with(this).load(musicNow.getMusicMediumAlbum()).asBitmap().listener(listener).into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
    } else {//本地
        if (musicNow.getAlbumLink() != null) {
            Glide.with(this)
                    .load(musicNow.getAlbumLink())
                    .asBitmap()
                    .placeholder(R.drawable.default_album)
                    .listener(listener)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        } else {
            Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
            Uri uri = ContentUris.withAppendedId(sArtworkUri, musicNow.getMusicAlbumId());
            Glide.with(this).load(uri).asBitmap().listener(listener).into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        }
    }
}
 
Example 6
Source Project: MoeGallery   Source File: ImageFragment.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean onResourceReady(final V resource, T model, Target<V> target,
        boolean isFromMemoryCache,
        boolean isFirstResource) {
    width = resource.getIntrinsicWidth();
    height = resource.getIntrinsicHeight();

    if (isVisibleToUser) {
        updateOrientation();

        if (getActivity() != null) {
            ((MainActivity) getActivity()).setTouchEventListener(ImageFragment.this);
        }
    }

    if (resource instanceof Animatable) {
        mHandler.removeCallbacks(mUpdateGifRunnable);
        mHandler.postDelayed(mUpdateGifRunnable, 10);
    }
    mProgressBar.setVisibility(View.GONE);
    return false;
}
 
Example 7
Source Project: Easy_xkcd   Source File: FavoritesFragment.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... dummy) {
    DatabaseManager databaseManager = new DatabaseManager(getActivity());
    while (!favStack.isEmpty()) {
        try {
            //RealmComic comic = RealmComic.findNewestComic(Realm.getDefaultInstance(), getActivity());
            RealmComic comic = databaseManager.getRealmComic(favStack.pop());
            mBitmap = Glide
                    .with(getActivity())
                    .asBitmap()
                    .load(comic.getUrl())
                    //.diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) //TODO replace all .into(-1,-1) with the simple target
                    .get();
            RealmComic.saveOfflineBitmap(mBitmap, prefHelper, comic.getComicNumber(), getActivity());
            Timber.d("comic %d saved...", comic.getComicNumber());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 8
public Target<Drawable> load(String url, ImageView imageView) {
  Context context = weakContext.get();
  if (context != null) {
    String newImageUrl = AptoideUtils.IconSizeU.getNewImageUrl(url, resources, windowManager);
    if (newImageUrl != null) {
      Uri uri = Uri.parse(newImageUrl);
      return Glide.with(context)
          .load(uri)
          .apply(getRequestOptions())
          .transition(DrawableTransitionOptions.withCrossFade())
          .into(imageView);
    } else {
      Log.e(TAG, "newImageUrl is null");
    }
  } else {
    Log.e(TAG, "::load() Context is null");
  }
  return null;
}
 
Example 9
Source Project: Moment   Source File: RxDownload.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Observable<File> get(RequestManager requestManager, String url) {
    return Observable.create(new Observable.OnSubscribe<File>() {
        @Override
        public void call(Subscriber<? super File> subscriber) {
            try {
                subscriber.onNext(requestManager.load(url)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get());
            } catch (InterruptedException | ExecutionException e) {
                subscriber.onError(e);
            } finally {
                subscriber.onCompleted();
            }
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());

}
 
Example 10
Source Project: YiZhi   Source File: ImageBrowseActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 保存图片到本地
 *
 * @param fileName 文件名
 */
private void saveImageToLocal(final String fileName) {
    Observable.create(new ObservableOnSubscribe<File>() {
        @Override
        public void subscribe(ObservableEmitter<File> e) throws Exception {
            e.onNext(Glide.with(ImageBrowseActivity.this)
                    .load(mImageUrl)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get());
            e.onComplete();
        }
    }).compose(RxHelper.<File>rxSchedulerHelper()).subscribe(new Consumer<File>() {
        @Override
        public void accept(File file) throws Exception {
            saveImage(fileName, file);
        }
    });
}
 
Example 11
Source Project: glide-support   Source File: DetailFragment.java    License: The Unlicense 6 votes vote down vote up
private void setupGlide() {
	thumb = Glide
			.with(this)
			.using(new NetworkDisablingLoader<>()) // make sure we're hitting some cache (optional)
			// everything has to match the grid's adapter to hit the memory cache
			.load(item.thumbUrl)
			.override(256, 256)
			.centerCrop()
			.listener(THUMB_LOGGER) // irrelevant for cache
	;
	int width = getActivity().getWindow().getDecorView().getWidth(); // this assumes that the fragment is created
	// from an existing fragment inside the same activity (list-detail), otherwise getWidth() may be 0
	full = Glide
			.with(this)
			.load(item.fullUrl)
			.override(width, Target.SIZE_ORIGINAL)
			.listener(FULL_LOGGER)
	;
}
 
Example 12
Source Project: MoeQuest   Source File: MeiziDetailsFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onResourceReady(GlideDrawable resource, String model,
                               Target<GlideDrawable> target, boolean
                                   isFromMemoryCache, boolean isFirstResource) {

  mImageView.setImageDrawable(resource);
  mPhotoViewAttacher = new PhotoViewAttacher(mImageView);
  mImageError.setVisibility(View.GONE);
  setPhotoViewAttacher();
  return false;
}
 
Example 13
Source Project: PainlessMusicPlayer   Source File: NowPlayingActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onLoadFailed(
        @Nullable final GlideException e,
        @NonNull final Object model,
        @NonNull final Target<Drawable> target,
        final boolean isFirstResource) {
    albumArt.setAlpha(0f);
    albumArt.setImageResource(R.drawable.album_art_placeholder);
    albumArt.animate().alpha(1f).start();
    onArtProcessed();
    return true;
}
 
Example 14
Source Project: android-tutorials-glide   Source File: UsageExampleErrorLogging.java    License: MIT License 5 votes vote down vote up
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
    // todo log exception

    // important to return false so the error placeholder can be placed
    return false;
}
 
Example 15
Source Project: Mysplash   Source File: ImageHelper.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Bitmap loadBitmap(Context context, @DrawableRes int id, @Nullable @Size(2) int[] size)
        throws ExecutionException, InterruptedException {
    if (size == null) {
        size = new int[] {Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL};
    }
    return Glide.with(getValidContext(context))
            .load(id)
            .asBitmap()
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(size[0], size[1])
            .get();
}
 
Example 16
public Target<Drawable> loadUsingCircleTransform(@NonNull String url,
    @NonNull ImageView imageView) {
  Context context = weakContext.get();
  if (context != null) {
    return Glide.with(context)
        .load(url)
        .apply(getRequestOptions().transform(new CircleCrop()))
        .transition(DrawableTransitionOptions.withCrossFade())
        .into(imageView);
  } else {
    Log.e(TAG, "::loadUsingCircleTransform() Context is null");
  }
  return null;
}
 
Example 17
public Target<Drawable> loadWithShadowCircleTransform(String url, ImageView imageView,
    @ColorInt int color, float spaceBetween, float strokeSize) {
  Context context = weakContext.get();
  if (context != null) {
    return Glide.with(context)
        .load(url)
        .apply(getRequestOptions().transform(
            new ShadowCircleTransformation(context, imageView, color, spaceBetween, strokeSize)))
        .transition(DrawableTransitionOptions.withCrossFade())
        .into(imageView);
  } else {
    Log.e(TAG, "::loadWithShadowCircleTransform() Context is null");
  }
  return null;
}
 
Example 18
Source Project: ShareBox   Source File: FileExpandableAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
    if (model instanceof String) {
        CacheUtil.makeCache((String) model, ImageUtil.drawable2Bitmap(resource), resource.getIntrinsicWidth(),
                resource.getIntrinsicHeight(), mContext);
    }
    return false;
}
 
Example 19
Source Project: glide-support   Source File: TestFragment.java    License: The Unlicense 5 votes vote down vote up
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
	super.onViewCreated(view, savedInstanceState);
	new AsyncTask<Void, Void, Point>() {
		String url = "http://imgfave-herokuapp-com.global.ssl.fastly.net/image_cache/142083463797243_tall.jpg";
		//String url = "https://upload.wikimedia.org/wikipedia/commons/a/a3/Berliner_Fernsehturm,_Sicht_vom_Neptunbrunnen_-_Berlin_Mitte.jpg";
		@Override protected Point doInBackground(Void... params) {
			try {
				File image = Glide
						.with(TestFragment.this)
						.load(url)
						.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
						.get();
				Options opts = new Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(image.getAbsolutePath(), opts);
				return new Point(opts.outWidth, opts.outHeight);
			} catch (InterruptedException | ExecutionException ignored) {
				return null;
			}
		}
		@Override protected void onPostExecute(Point imageSize) {
			if (imageSize != null) {
				listView.setAdapter(new ImageChunkAdapter(getScreenSize(), url, imageSize));
			}
		}
	}.execute();
}
 
Example 20
@Override
public boolean onResourceReady(PictureDrawable resource, T model
        , Target<PictureDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
    ImageView view = ((ImageViewTarget<?>) target).getView();
    if (Build.VERSION_CODES.HONEYCOMB <= Build.VERSION.SDK_INT) {
        view.setLayerType(ImageView.LAYER_TYPE_SOFTWARE, null);
    }
    return false;
}
 
Example 21
public Target<Drawable> loadUsingCircleTransformAndPlaceholder(String url, ImageView imageView,
    @DrawableRes int defaultImagePlaceholder) {
  Context context = weakContext.get();
  if (context != null) {
    return Glide.with(context)
        .load(url)
        .apply(getRequestOptions().transform(new CircleCrop())
            .placeholder(defaultImagePlaceholder))
        .transition(DrawableTransitionOptions.withCrossFade())
        .into(imageView);
  } else {
    Log.e(TAG, "::loadUsingCircleTransformAndPlaceholder() Context is null");
  }
  return null;
}
 
Example 22
public Target<Drawable> loadWithShadowCircleTransform(@DrawableRes int drawableId,
    ImageView imageView) {
  Context context = weakContext.get();
  if (context != null) {
    return Glide.with(context)
        .load(drawableId)
        .apply(getRequestOptions().transform(new ShadowCircleTransformation(context, imageView)))
        .transition(DrawableTransitionOptions.withCrossFade())
        .into(imageView);
  } else {
    Log.e(TAG, "::loadWithShadowCircleTransform() Context is null");
  }
  return null;
}
 
Example 23
Source Project: StatusStories   Source File: LoggingListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onResourceReady(B resource, A model, Target<B> target, boolean isFromMemoryCache,
                               boolean isFirstResource) {
    String resourceString = strip(getResourceDescription(resource));
    String targetString = strip(getTargetDescription(target));
    Log.println(level, "GLIDE", String.format(Locale.ROOT,
            "%s.onResourceReady(%s, %s, %s, %s, %s)",
            name, resourceString, model, targetString, isMem(isFromMemoryCache), isFirst(isFirstResource)));
    return delegate.onResourceReady(resource, model, target, isFromMemoryCache, isFirstResource);
}
 
Example 24
Source Project: Twire   Source File: ChannelActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void initStreamerImageAndColors() {
    Target<Bitmap> mTarget = getNightThemeTarget();
    String theme = new Settings(this).getTheme();
    if (!theme.equals(getString(R.string.night_theme_name)) && !theme.equals(getString(R.string.true_night_theme_name))) {
        mTarget = getLightThemeTarget();
    }

    Glide.with(getBaseContext())
            .asBitmap()
            .load(info.getMediumPreview())
            .into(mTarget);
}
 
Example 25
Source Project: Twire   Source File: ChannelActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Target<Bitmap> getNightThemeTarget() {
    return new CustomTarget<Bitmap>() {
        @Override
        public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition)  {
            streamerImage.setImageBitmap(bitmap);
        }

        @Override
        public void onLoadCleared(@Nullable Drawable placeholder) {

        }
    };
}
 
Example 26
public DrawableRequestBuilder<GlideDrawable> build() {
    //noinspection unchecked
    return createBaseRequest(requestManager, artist, noCustomImage)
            .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY)
            .error(DEFAULT_ERROR_IMAGE)
            .animate(DEFAULT_ANIMATION)
            .priority(Priority.LOW)
            .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
            .signature(createSignature(artist));
}
 
Example 27
public Target<Drawable> loadWithShadowCircleTransformWithPlaceholder(String url,
    ImageView imageView, @DrawableRes int drawablePlaceholder) {
  Context context = weakContext.get();
  if (context != null) {
    return Glide.with(context)
        .load(url)
        .apply(getRequestOptions().transform(new ShadowCircleTransformation(context))
            .placeholder(drawablePlaceholder))
        .transition(DrawableTransitionOptions.withCrossFade())
        .into(imageView);
  } else {
    Log.e(TAG, "::loadWithShadowCircleTransform() Context is null");
  }
  return null;
}
 
Example 28
Source Project: Markwon   Source File: GlideImagesPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void cancel(@NonNull AsyncDrawable drawable) {
    final Target<?> target = cache.remove(drawable);
    if (target != null) {
        glideStore.cancel(target);
    }
}
 
Example 29
Source Project: imsdk-android   Source File: ProfileUtils.java    License: MIT License 5 votes vote down vote up
public static void displayEmojiconByImageSrc(final Activity context, final String imageSrc, final ImageView headView, final int w, final int h){

        if(context == null){
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if(context.isDestroyed()){
                return;
            }
        }
        if(TextUtils.isEmpty(imageSrc) || headView == null){
            return;
        }
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //glide
                Glide.with(context)
                        //配置上下文
                        .load(imageSrc)
//                        .load(new MyGlideUrl(imageSrc))      //设置图片路径(fix #8,文件名包含%符号 无法识别和显示)
                        .asBitmap()
//                        .error(defaultRes)
                        .centerCrop()
                        .thumbnail(0.1f)
                        .transform(new CenterCrop(context))
                        .placeholder(defaultRes)
                        .override(w > 0 ? w + 5 : Target.SIZE_ORIGINAL, h > 0 ? h + 5 : Target.SIZE_ORIGINAL)
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)//缓存全尺寸
                        .dontAnimate()
                        .into(headView);
            }
        });



    }
 
Example 30
Source Project: PainlessMusicPlayer   Source File: QueueActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onLoadFailed(
        @Nullable final GlideException e,
        @NonNull final Object model,
        @NonNull final Target<Drawable> target,
        final boolean isFirstResource) {
    mCoverUri = null;
    showPlaceholderArt();
    onImageSet();
    return true;
}