@Override protected void load(final Context context) throws Exception { String profileUrl = "..."; long lastProfileCache = context.getSharedPreferences("profile", 0) .getLong("lastCacheTime", System.currentTimeMillis()); Glide // display a fresh version .with(context) .load(profileUrl) .thumbnail(Glide // display a cached version .with(context) .using(new NetworkDisablingLoader<>()) // only if exists in disk cache .load(profileUrl) .signature(new StringSignature(String.valueOf(lastProfileCache))) .diskCacheStrategy(SOURCE) ) .diskCacheStrategy(NONE) // downloaded right now .into(imageView) ; }
private void cache(String url, final Bitmap bitmap) { Key key = new StringSignature(url); // the key here is that Engine uses fetcher.getId() for constructing OriginalKey from EngineKey // see Engine.load and also signature can be ignored because it is an EmptySignature instance for most App.getInstance().getDiskCache().put(key, new Writer() { @TargetApi(VERSION_CODES.KITKAT) // for try-with-resources @Override public boolean write(File file) { try (OutputStream out = new FileOutputStream(file)) { // mimic default behavior you can also use Bitmap.compress BitmapPool pool = Glide.get(getContext()).getBitmapPool(); BitmapResource resource = BitmapResource.obtain(bitmap, pool); new BitmapEncoder().encode(resource, out); return true; } catch (IOException e) { e.printStackTrace(); return false; } } }); }
@Override public Object instantiateItem(final ViewGroup container, int position) { final PhotoView view = new PhotoView(ImageBrowserActivity.this); view.setScaleType(ImageView.ScaleType.FIT_CENTER); ImageFile file = mList.get(position); RequestManager requestManager = Glide.with(ImageBrowserActivity.this); DrawableRequestBuilder requestBuilder; if (file.getEditCount() > 0) { requestBuilder = requestManager.load(file.getEditedPath()) .signature(new StringSignature(file.getEditCount() + "")); } else { requestBuilder = requestManager.load(file.getPath()); } requestBuilder .crossFade() .placeholder(R.mipmap.ic_place_holder).into(view); container.addView(view); return view; }
@Override public void onBindViewHolder(final AnchorHotViewHolder holder, final int position) { Glide.with(mContext).load(mData.get(position)).signature(new StringSignature(new Random().nextInt(1000) + "")).into(holder.iv_item_donate); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, ImagePagerActivity.class); // 图片url,为了演示这里使用常量,一般从数据库中或网络中获取 intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, formatPic()); intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position); mContext.startActivity(intent); ((Activity) mContext).overridePendingTransition(R.anim.zoomin, 0); } }); }
@SuppressWarnings("unchecked") @Override protected void load(Context context) { GenericRequestBuilder<Bitmap, Bitmap, Bitmap, Bitmap> glide = Glide .with(context) .using(new PassthroughModelLoader<Bitmap, Bitmap>(), Bitmap.class) .from(Bitmap.class) .as(Bitmap.class) .decoder(new BitmapBitmapResourceDecoder(context)) .cacheDecoder(new FileToStreamDecoder<Bitmap>(new StreamBitmapDecoder(context))) .encoder(new BitmapEncoder()) // or .diskCacheStrategy(DiskCacheStrategy.NONE) instead of last 2 ; // simulate a bitmap input Drawable drawable = ContextCompat.getDrawable(context, android.R.drawable.sym_def_app_icon); Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); glide .clone() .load(bitmap) .signature(new StringSignature("android.R.drawable.sym_def_app_icon")) // required for caching .diskCacheStrategy(DiskCacheStrategy.NONE) // but can't really cache it, see #122 comments .transform(new CenterCrop(context)) .into(imageView) ; }
@Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { ImageThumbnailHolder viewHolder = (ImageThumbnailHolder) holder; ImageFile file = mSelectedThumbnailList.get(position); RequestManager requestManager = Glide.with(ImageBrowserActivity.this); DrawableRequestBuilder requestBuilder; if (file.getEditCount() > 0) { requestBuilder = requestManager.load(file.getEditedPath()) .signature(new StringSignature(file.getEditCount() + "")); } else { requestBuilder = requestManager.load(file.getPath()); } requestBuilder.centerCrop() .crossFade() .placeholder(R.mipmap.ic_place_holder).into(viewHolder.imageView); if (mList.get(mCurrentIndex).getId() == file.getId()) { viewHolder.ivBlock.setVisibility(View.VISIBLE); } else { viewHolder.ivBlock.setVisibility(View.GONE); } if (mIsPreview) { viewHolder.shadow.setVisibility(file.isSelected() ? View.GONE : View.VISIBLE); } viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(Integer.valueOf(mSelectedPosition.get(position)), false); mRecyclerView.scrollToPosition(position); } }); }
public void uploadIconSucceed(File file, String token) { qiniuToken = token; Glide.with(context).load(file).asBitmap().centerCrop().signature(new StringSignature(new Date().getTime() + "")).into(new BitmapImageViewTarget(iv_info_icon) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource); circularBitmapDrawable.setCircular(true); iv_info_icon.setImageDrawable(circularBitmapDrawable); } }); }
private void updateProfileCache(final Context context, String profileUrl) { final long lastProfileCache = System.currentTimeMillis(); Glide .with(context) .load(profileUrl) .signature(new StringSignature(String.valueOf(lastProfileCache))) .diskCacheStrategy(SOURCE) .listener(new SaveLastProfileCacheTime(context, lastProfileCache)) .preload() ; }
@Override protected void load(final Context context) throws Exception { final ImageView imageView = this.imageView; toto = toto + 1; Glide .with(context.getApplicationContext()) .load("http://lorempixel.com/400/200/sports") .signature(new StringSignature(Integer.toString(toto))) .centerCrop() .listener(new LoggingListener<String, GlideDrawable>()) .into(imageView) ; }
@Override protected void load1(Context context, ImageView imageView) throws Exception { Glide .with(this) // default timeout is 2.5 seconds (com.bumptech.glide.load.data.HttpUrlFetcher) .load("https://httpbin.org/delay/12") // force a timeout: 2.5 < 12 .signature(new StringSignature("load1")) // distinguish from other load to make sure loader is picked up .placeholder(R.drawable.glide_placeholder) .error(R.drawable.glide_error) .listener(new LoggingListener<String, GlideDrawable>("load1")) .into(new LoggingTarget<>("load1", Log.VERBOSE, new GlideDrawableImageViewTarget(imageView))) ; }
@Override protected void load2(Context context, ImageView imageView) throws Exception { Glide .with(this) .using(new StreamModelLoaderWrapper<>(new OkHttpUrlLoader(longTimeoutClient))) .load(new GlideUrl("https://httpbin.org/delay/12")) // timeout increased: 15 > 10, so it'll pass .signature(new StringSignature("load2")) // distinguish from other load to make sure loader is picked up .placeholder(R.drawable.glide_placeholder) // since the test URL returns a JSON stream, the load will fail, // let's still add an error to see that the load fails slower than the other, // meaning the image was actually tried to be decoded .error(R.drawable.glide_error) .listener(new LoggingListener<GlideUrl, GlideDrawable>("load2")) .into(new LoggingTarget<>("load2", Log.VERBOSE, new GlideDrawableImageViewTarget(imageView))) ; }
@Override protected void onHandleIntent(Intent intent) { Uri imageUri = intent.getParcelableExtra(SOURCE_IMAGE_URI); String watermarkJson = intent.getStringExtra(WATERMARK_JSON); Watermark watermark = Watermark.fromJson(watermarkJson, getAssets()); String outputPath = intent.getStringExtra(OUTPUT_PATH); File outFile = new File(outputPath); int targetWidth = intent.getIntExtra(OUTPUT_WIDTH, 0); int targetHeight = intent.getIntExtra(OUTPUT_HEIGHT, 0); mOutputDestination = intent.getIntExtra(OUTPUT_DESTINATION, INTENT_EXPORT); Bitmap outputBitmap = null; Exception exception = null; try { // add signature so Glide reloads - otherwise it might use cached buffer which was written on outputBitmap = Glide.with(getApplicationContext()) .loadFromMediaStore(imageUri) .asBitmap() .signature(new StringSignature(ImageUtil.getTimestamp())) .into(targetWidth, targetHeight) .get(); } catch (InterruptedException | ExecutionException e) { exception = e; } if (exception != null) { String resultMessage = String.format("%s load error %s", TAG, exception.getMessage()); Log.e(TAG, resultMessage); publishResults("", RESULT_ERROR_CODE, resultMessage); } else { saveImageFile(outputBitmap, watermark, outFile); } }
private void saveImg(String url){ //检查是否有sd卡 if (saveDir == null) { showToast(R.string.save_not_sd); return; } // 检查本地是否有 String fileName = getFileNameByUrl(url); File localFile = new File(saveDir,fileName); if (localFile.exists()){ showToast(R.string.save_exist); return; } // 检查glide的disk是否有 DiskCache diskCache = DiskLruCacheWrapper.get(cacheDir, App.DEFAULT_DISK_CACHE_SIZE); File diskTempFile = diskCache.get(new StringSignature(url)); if (diskTempFile == null || !diskTempFile.exists()){ showToast(R.string.save_not_downloaded); return; } // 检查是否在队列中 if (mUrlSet.contains(url)){ showToast(R.string.save_saving); return; } mExecutorService.execute(new SaveImgRunnable(url,diskTempFile.getAbsolutePath(),localFile.getAbsolutePath())); mUrlSet.add(url); showToast(R.string.save_start); }
public GlidePhotoData(Activity activity, ImageView view, int defaultResID, String lastModify, int maxsize, String subdomain, String url) { mImageView = view; mIdentify = subdomain + url; mUrl = url; mMaxSize = maxsize; Glide.with(activity) .load(url) .placeholder(defaultResID) .signature(new StringSignature(lastModify)) .decoder(mResourceDecoder) .crossFade() .fitCenter() .into(mImageView); }
public GlidePhotoData(Activity activity, ImageView view, String lastModify, int maxsize, String subdomain, String url) { mImageView = view; mIdentify = subdomain + url; mUrl = url; mMaxSize = maxsize; Glide.with(activity) .load(url) .signature(new StringSignature(lastModify)) .decoder(mResourceDecoder) .crossFade() .fitCenter() .into(mImageView); }
public static void loadAvatar(RequestManager glide, ImageView view, String avatarUrl) { String cacheKey = null; if (avatarUrl != null) cacheKey = AVATAR_CACHE_KEYS.get(avatarUrl); if (cacheKey == null) { if (avatarUrl == null || NOT_FOUND_AVATARS.containsKey(avatarUrl)) { avatarUrl = DEFAULT_AVATAR_FILE.getAbsolutePath(); } cacheKey = avatarUrl; } if (HiSettingsHelper.getInstance().isCircleAvatar()) { glide.load(avatarUrl) .signature(new StringSignature(cacheKey)) .diskCacheStrategy(DiskCacheStrategy.NONE) .bitmapTransform(new CropCircleTransformation(HiApplication.getAppContext())) .error(DEFAULT_USER_ICON) .crossFade() .into(view); } else { glide.load(avatarUrl) .signature(new StringSignature(cacheKey)) .diskCacheStrategy(DiskCacheStrategy.NONE) .centerCrop() .error(DEFAULT_USER_ICON) .crossFade() .into(view); } }
@Override public void onBindViewHolder(SmartListViewHolder holder, int position) { final SmartListViewModel smartListViewModel = mSmartListViewModels.get(position); holder.convParticipants.setText(smartListViewModel.getContactName()); long lastInteraction = smartListViewModel.getLastInteractionTime(); String lastInteractionStr = lastInteraction == 0 ? "" : DateUtils.getRelativeTimeSpanString(lastInteraction, System.currentTimeMillis(), 0L, DateUtils.FORMAT_ABBREV_ALL).toString(); holder.convTime.setText(lastInteractionStr); if (smartListViewModel.hasOngoingCall()) { holder.convStatus.setText(holder.itemView.getContext().getString(R.string.ongoing_call)); } else if (smartListViewModel.getLastInteraction() != null) { holder.convStatus.setText(getLastInteractionSummary(smartListViewModel.getLastEntryType(), smartListViewModel.getLastInteraction(), holder.itemView.getContext())); } else { holder.convStatus.setVisibility(View.GONE); } if (smartListViewModel.hasUnreadTextMessage()) { holder.convParticipants.setTypeface(null, Typeface.BOLD); holder.convTime.setTypeface(null, Typeface.BOLD); holder.convStatus.setTypeface(null, Typeface.BOLD); } else { holder.convParticipants.setTypeface(null, Typeface.NORMAL); holder.convTime.setTypeface(null, Typeface.NORMAL); holder.convStatus.setTypeface(null, Typeface.NORMAL); } if (smartListViewModel.getPhotoData() != null) { Glide.with(holder.itemView.getContext()) .fromBytes() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(false) .load(smartListViewModel.getPhotoData()) .crossFade() .signature(new StringSignature(String.valueOf(Arrays.hashCode(smartListViewModel.getPhotoData())))) .placeholder(R.drawable.ic_contact_picture) .transform(new CircleTransform(holder.itemView.getContext())) .error(R.drawable.ic_contact_picture) .into(holder.photo); } else { Glide.with(holder.itemView.getContext()) .load(R.drawable.ic_contact_picture) .crossFade() .signature(new StringSignature(smartListViewModel.getUuid())) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(holder.photo); } holder.online.setVisibility(smartListViewModel.isOnline() ? View.VISIBLE : View.GONE); holder.bind(listener, smartListViewModel); }
public static void loadFriendProfileImg(Context context, String username, ImageView view) { Glide.with(context).load(URLs.PROFILE_URL + username + ".JPEG") .signature(new StringSignature(Utility.getTime(Calendar.HOUR_OF_DAY))) .dontAnimate().error(R.drawable.photo).into(view); }
public StringSignature getArtistSignature(String artistName) { return new StringSignature(String.valueOf(getArtistSignatureRaw(artistName))); }
@Override public void onBindViewHolder(final ViewHolder viewHolder, final int position) { viewHolder.itemView.setClickable(true); viewHolder.itemView.setActivated(mSelectedItems.get(position, false)); entry = mItems.get(position); date = entry.creationDate; description = entry.text; tags = entry.tags; starred = entry.starred; emptyCal.set(Calendar.DAY_OF_MONTH, date.get(Calendar.DAY_OF_MONTH)); emptyCal.set(Calendar.MONTH, date.get(Calendar.MONTH)); emptyCal.set(Calendar.YEAR, date.get(Calendar.YEAR)); viewHolder.title.setText(entry.title); if (description != null) viewHolder.description.setText(description.substring(0, Math.min(description.length(), 400))); viewHolder.timeOfDay.setText(timeFormat.format(date.getTime())); if (entry.photos.isEmpty()) { viewHolder.thumbnail.setVisibility(View.GONE); viewHolder.dayOfMonth.setVisibility(View.VISIBLE); viewHolder.dayOfMonth.setText(String.valueOf(entry.creationDate.get(Calendar.DAY_OF_MONTH))); if (!colorDates.contains(emptyCal.getTimeInMillis())) { int index = mBackgroundCount++ % mCircleBackgrounds.length; if (Build.VERSION.SDK_INT >= 16) viewHolder.dayOfMonth.setBackground(mCircleBackgrounds[index]); else viewHolder.dayOfMonth.setBackgroundDrawable(mCircleBackgrounds[index]); viewHolder.dayOfMonth.setTag(index); colorMap.put(emptyCal.getTimeInMillis(), index); colorDates.add(emptyCal.getTimeInMillis()); } else { if (Build.VERSION.SDK_INT >= 16) viewHolder.dayOfMonth.setBackground(mCircleBackgrounds[colorMap.get(emptyCal.getTimeInMillis())]); else viewHolder.dayOfMonth.setBackgroundDrawable(mCircleBackgrounds[colorMap.get(emptyCal.getTimeInMillis())]); } } else { viewHolder.dayOfMonth.setVisibility(View.GONE); viewHolder.thumbnail.setVisibility(View.VISIBLE); String path = entry.photos.get(0).path; File image = new File(path); Glide.with(GlobalApplication.getAppContext()) .load(path) .transform(mRoundCornerTransformation) .placeholder(R.color.transparent) .signature(new StringSignature(String.valueOf(image.lastModified()))) .into(viewHolder.thumbnail); } if (starred) { viewHolder.bookmark.setVisibility(View.VISIBLE); } else { viewHolder.bookmark.setVisibility(View.INVISIBLE); } }