Java Code Examples for com.facebook.imagepipeline.request.ImageRequest

The following are top voted examples for showing how to use com.facebook.imagepipeline.request.ImageRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: PipelineDraweeControllerBuilder.java   Source Code and License 6 votes vote down vote up
private CacheKey getCacheKey() {
  final ImageRequest imageRequest = getImageRequest();
  final CacheKeyFactory cacheKeyFactory = mImagePipeline.getCacheKeyFactory();
  CacheKey cacheKey = null;
  if (cacheKeyFactory != null && imageRequest != null) {
    if (imageRequest.getPostprocessor() != null) {
      cacheKey = cacheKeyFactory.getPostprocessedBitmapCacheKey(
          imageRequest,
          getCallerContext());
    } else {
      cacheKey = cacheKeyFactory.getBitmapCacheKey(
          imageRequest,
          getCallerContext());
    }
  }
  return cacheKey;
}
 
Example 2
Project: GitHub   File: ForwardingRequestListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onRequestFailure(
    ImageRequest request,
    String requestId,
    Throwable throwable,
    boolean isPrefetch) {
  final int numberOfListeners = mRequestListeners.size();
  for (int i = 0; i < numberOfListeners; ++i) {
    RequestListener listener = mRequestListeners.get(i);
    try {
      listener.onRequestFailure(request, requestId, throwable, isPrefetch);
    } catch (Exception exception) {
      // Don't punish the other listeners if we're given a bad one.
      onException("InternalListener exception in onRequestFailure", exception);
    }
  }
}
 
Example 3
Project: GitHub   File: RequestLoggingListener.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized void onRequestFailure(
    ImageRequest request,
    String requestId,
    Throwable throwable,
    boolean isPrefetch) {
  if (FLog.isLoggable(FLog.WARN)) {
    Long startTime = mRequestStartTimeMap.remove(requestId);
    long currentTime = getTime();
    FLog.w(
        TAG,
        "time %d: onRequestFailure: {requestId: %s, elapsedTime: %d ms, throwable: %s}",
        currentTime,
        requestId,
        getElapsedTime(startTime, currentTime),
        throwable.toString());
  }
}
 
Example 4
Project: GitHub   File: BitmapMemoryCacheGetProducerTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  mBitmapMemoryCacheGetProducer =
      new BitmapMemoryCacheGetProducer(mMemoryCache, mCacheKeyFactory, mInputProducer);
  mCloseableImage1 = mock(CloseableImage.class);
  mFinalImageReference = CloseableReference.of(mCloseableImage1);
  when(mCloseableImage1.getQualityInfo()).thenReturn(ImmutableQualityInfo.FULL_QUALITY);

  when(mProducerContext.getImageRequest()).thenReturn(mImageRequest);
  when(mProducerContext.getListener()).thenReturn(mProducerListener);
  when(mProducerContext.getId()).thenReturn(mRequestId);
  when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
  when(mProducerContext.getLowestPermittedRequestLevel())
      .thenReturn(ImageRequest.RequestLevel.FULL_FETCH);
  when(mProducerContext.getCallerContext())
      .thenReturn(PRODUCER_NAME);
  when(mCacheKeyFactory.getBitmapCacheKey(mImageRequest, PRODUCER_NAME)).thenReturn(mCacheKey);
}
 
Example 5
Project: GitHub   File: ImagePipelineTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetBitmapCacheGetSupplier() {
  Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier =
      mImagePipeline.getDataSourceSupplier(
          mImageRequest,
          mCallerContext,
          ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
  Producer<CloseableReference<CloseableImage>> bitmapCacheSequence = mock(Producer.class);
  when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest))
      .thenReturn(bitmapCacheSequence);
  dataSourceSupplier.get();
  verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0",  false);
  verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false);
  ArgumentCaptor<ProducerContext> producerContextArgumentCaptor =
      ArgumentCaptor.forClass(ProducerContext.class);
  verify(bitmapCacheSequence)
      .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture());
  assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected());
  assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH);
}
 
Example 6
Project: GitHub   File: DiskCacheReadProducerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSmallImageDiskCacheGetNotFoundInputProducerSuccess() {
  when(mImageRequest.getCacheChoice()).thenReturn(ImageRequest.CacheChoice.SMALL);
  setupDiskCacheGetNotFound(mSmallImageBufferedDiskCache);
  setupInputProducerSuccess();
  mDiskCacheReadProducer.produceResults(mConsumer, mProducerContext);
  verify(mConsumer).onNewResult(mFinalEncodedImage, Consumer.IS_LAST);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  ArgumentCaptor<HashMap> captor = ArgumentCaptor.forClass(HashMap.class);
  verify(mProducerListener).onProducerFinishWithSuccess(
      eq(mRequestId), eq(PRODUCER_NAME), captor.capture());
  Map<String, String> resultMap = captor.getValue();
  assertEquals("false", resultMap.get(DiskCacheReadProducer.EXTRA_CACHED_VALUE_FOUND));
  assertNull(resultMap.get(DiskCacheReadProducer.ENCODED_IMAGE_SIZE));
  verify(mProducerListener, never())
      .onUltimateProducerReached(anyString(), anyString(), anyBoolean());
}
 
Example 7
Project: GitHub   File: LocalResourceFetchProducer.java   Source Code and License 6 votes vote down vote up
private int getLength(ImageRequest imageRequest) {
  AssetFileDescriptor fd = null;
  try {
    fd = mResources.openRawResourceFd(getResourceId(imageRequest));
    return (int) fd.getLength();
  } catch (Resources.NotFoundException e) {
    return -1;
  } finally {
    try {
      if (fd != null) {
        fd.close();
      }
    } catch (IOException ignored) {
      // There's nothing we can do with the exception when closing descriptor.
    }
  }
}
 
Example 8
Project: GitHub   File: QualifiedResourceFetchProducerTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  mExecutor = new TestExecutorService(new FakeClock());
  mQualifiedResourceFetchProducer = new QualifiedResourceFetchProducer(
      mExecutor,
      mPooledByteBufferFactory,
      mContentResolver);
  mContentUri = UriUtil.getUriForQualifiedResource(PACKAGE_NAME, RESOURCE_ID);

  mProducerContext = new SettableProducerContext(
      mImageRequest,
      REQUEST_ID,
      mProducerListener,
      CALLER_CONTEXT,
      ImageRequest.RequestLevel.FULL_FETCH,
      false,
      true,
      Priority.MEDIUM);
  when(mImageRequest.getSourceUri()).thenReturn(mContentUri);
}
 
Example 9
Project: GitHub   File: ProducerSequenceFactoryTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  PowerMockito.mockStatic(UriUtil.class, MediaUtils.class);

  ProducerFactory producerFactory = mock(ProducerFactory.class, RETURNS_MOCKS);

  mProducerSequenceFactory = new ProducerSequenceFactory(
      RuntimeEnvironment.application.getContentResolver(),
      producerFactory,
      null,
      true,
      false,
      null,
      false,
      false,
      false);

  when(mImageRequest.getLowestPermittedRequestLevel())
      .thenReturn(ImageRequest.RequestLevel.FULL_FETCH);
  mUri = Uri.parse("http://dummy");
  when(mImageRequest.getSourceUri()).thenReturn(mUri);
  when(MediaUtils.extractMime(mUri.getPath())).thenReturn(mDummyMime);
  when(MediaUtils.isVideo(mDummyMime)).thenReturn(false);
}
 
Example 10
Project: GitHub   File: SettableProducerContext.java   Source Code and License 6 votes vote down vote up
public SettableProducerContext(
    ImageRequest imageRequest,
    String id,
    ProducerListener producerListener,
    Object callerContext,
    ImageRequest.RequestLevel lowestPermittedRequestLevel,
    boolean isPrefetch,
    boolean isIntermediateResultExpected,
    Priority priority) {
  super(
      imageRequest,
      id,
      producerListener,
      callerContext,
      lowestPermittedRequestLevel,
      isPrefetch,
      isIntermediateResultExpected,
      priority);
}
 
Example 11
Project: GitHub   File: BranchOnSeparateImagesProducer.java   Source Code and License 6 votes vote down vote up
@Override
protected void onNewResultImpl(EncodedImage newResult, @Status int status) {
  ImageRequest request = mProducerContext.getImageRequest();
  boolean isLast = isLast(status);
  boolean isGoodEnough =
      ThumbnailSizeChecker.isImageBigEnough(newResult, request.getResizeOptions());
  if (newResult != null && (isGoodEnough || request.getLocalThumbnailPreviewsEnabled())) {
    if (isLast && isGoodEnough) {
      getConsumer().onNewResult(newResult, status);
    } else {
      int alteredStatus = turnOffStatusFlag(status, IS_LAST);
      getConsumer().onNewResult(newResult, alteredStatus);
    }
  }
  if (isLast && !isGoodEnough) {
    EncodedImage.closeSafely(newResult);

    mInputProducer2.produceResults(getConsumer(), mProducerContext);
  }
}
 
Example 12
Project: GitHub   File: BitmapMemoryCacheProducerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBitmapMemoryCacheGetIntermediateImageLowestLevelReached() {
  setupBitmapMemoryCacheGetIntermediateImage();
  when(mProducerContext.getLowestPermittedRequestLevel())
      .thenReturn(ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
  mBitmapMemoryCacheProducer.produceResults(mConsumer, mProducerContext);
  verify(mConsumer).onNewResult(mIntermediateImageReference, Consumer.NO_FLAGS);
  verify(mConsumer).onNewResult(null, Consumer.IS_LAST);
  verify(mProducerListener).onProducerStart(mRequestId, PRODUCER_NAME);
  Map<String, String> extraMap =
      ImmutableMap.of(BitmapMemoryCacheProducer.EXTRA_CACHED_VALUE_FOUND, "false");
  verify(mProducerListener).onProducerFinishWithSuccess(mRequestId, PRODUCER_NAME, extraMap);
  verify(mProducerListener).onUltimateProducerReached(mRequestId, PRODUCER_NAME, false);
  Assert.assertTrue(!mIntermediateImageReference.isValid());
  verifyNoMoreInteractions(mInputProducer);
}
 
Example 13
Project: GitHub   File: DiskCacheReadProducer.java   Source Code and License 6 votes vote down vote up
public void produceResults(
    final Consumer<EncodedImage> consumer,
    final ProducerContext producerContext) {
  final ImageRequest imageRequest = producerContext.getImageRequest();
  if (!imageRequest.isDiskCacheEnabled()) {
    maybeStartInputProducer(consumer, producerContext);
    return;
  }

  producerContext.getListener().onProducerStart(producerContext.getId(), PRODUCER_NAME);

  final CacheKey cacheKey =
      mCacheKeyFactory.getEncodedCacheKey(imageRequest, producerContext.getCallerContext());
  final boolean isSmallRequest = (imageRequest.getCacheChoice() == CacheChoice.SMALL);
  final BufferedDiskCache preferredCache = isSmallRequest ?
      mSmallImageBufferedDiskCache : mDefaultBufferedDiskCache;
  final AtomicBoolean isCancelled = new AtomicBoolean(false);
  final Task<EncodedImage> diskLookupTask = preferredCache.get(cacheKey, isCancelled);
  final Continuation<EncodedImage, Void> continuation =
      onFinishDiskReads(consumer, producerContext);
  diskLookupTask.continueWith(continuation);
  subscribeTaskForRequestCancellation(isCancelled, producerContext);
}
 
Example 14
Project: GitHub   File: ImagePipelineTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFetchFromBitmapCacheDueToImageRequest() {
  Producer<CloseableReference<CloseableImage>> bitmapCacheSequence = mock(Producer.class);
  when(mImageRequest.getLowestPermittedRequestLevel())
      .thenReturn(ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
  when(mProducerSequenceFactory.getDecodedImageProducerSequence(mImageRequest))
      .thenReturn(bitmapCacheSequence);
  mImagePipeline.fetchDecodedImage(mImageRequest, mCallerContext);
  verify(mRequestListener1).onRequestStart(mImageRequest, mCallerContext, "0",  false);
  verify(mRequestListener2).onRequestStart(mImageRequest, mCallerContext, "0", false);
  ArgumentCaptor<ProducerContext> producerContextArgumentCaptor =
      ArgumentCaptor.forClass(ProducerContext.class);
  verify(bitmapCacheSequence)
      .produceResults(any(Consumer.class), producerContextArgumentCaptor.capture());
  assertTrue(producerContextArgumentCaptor.getValue().isIntermediateResultExpected());
  assertEquals(producerContextArgumentCaptor.getValue().getPriority(), Priority.HIGH);
  assertEquals(
      producerContextArgumentCaptor.getValue().getLowestPermittedRequestLevel(),
      ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE);
}
 
Example 15
Project: GitHub   File: MediaVariationsFragment.java   Source Code and License 6 votes vote down vote up
private void loadThumb(
    SimpleDraweeView draweeView,
    Size size,
    ImageRequest.RequestLevel requestLevel) {
  ImageRequest request = ImageRequestBuilder.newBuilderWithSource(size.uri)
      .setMediaVariations(MediaVariations.newBuilderForMediaId(MEDIA_ID)
          .setForceRequestForSpecifiedUri(true)
          .build())
      .setLowestPermittedRequestLevel(requestLevel)
      .setResizeOptions(new ResizeOptions(draweeView.getWidth(), draweeView.getHeight()))
      .setCacheChoice(size.cacheChoice)
      .build();
  DraweeController controller = Fresco.newDraweeControllerBuilder()
      .setImageRequest(request)
      .setOldController(draweeView.getController())
      .build();
  draweeView.setController(controller);
}
 
Example 16
Project: CommentGallery   File: CommentImageGrid.java   Source Code and License 6 votes vote down vote up
private void layoutChildrenView() {
    int childrenCount = getChildCount();

    for (int i = 0; i < childrenCount; i++) {
        ViewGroup childImageLayout = (ViewGroup) getChildAt(i);
        SimpleDraweeView childImageView = (SimpleDraweeView) childImageLayout.getChildAt(0);
        if (mOnItemClickListener != null) {
            final int finalI = i;
            childImageLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.OnItemClick(finalI);
                }
            });
        }
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(mImageUrls.get(i)))
                .setProgressiveRenderingEnabled(true)
                .setResizeOptions(new ResizeOptions(mItemWidth, mItemWidth))
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setOldController(childImageView.getController())
                .build();
        childImageView.setController(controller);

        int[] position = findPosition(i);
        int itemHeight = mItemWidth;
        int left = (int) (mItemWidth + mHorizontalSpace) * position[1];
        int top = (int) (itemHeight + mVerticalSpace) * position[0];
        int right = left + mItemWidth;
        int bottom = top + itemHeight;

        childImageLayout.layout(left, top, right, bottom);
    }
}
 
Example 17
Project: RNLearn_Project1   File: SystraceRequestListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onRequestFailure(
    ImageRequest request,
    String requestId,
    Throwable throwable,
    boolean isPrefetch) {
  if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) {
    return;
  }

  if (mRequestsID.containsKey(requestId)) {
    Pair<Integer, String> entry = mRequestsID.get(requestId);
    Systrace.endAsyncSection(
        Systrace.TRACE_TAG_REACT_FRESCO,
        entry.second,
        entry.first);
    mRequestsID.remove(requestId);
  }
}
 
Example 18
Project: RNLearn_Project1   File: SystraceRequestListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onRequestFailure(
    ImageRequest request,
    String requestId,
    Throwable throwable,
    boolean isPrefetch) {
  if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) {
    return;
  }

  if (mRequestsID.containsKey(requestId)) {
    Pair<Integer, String> entry = mRequestsID.get(requestId);
    Systrace.endAsyncSection(
        Systrace.TRACE_TAG_REACT_FRESCO,
        entry.second,
        entry.first);
    mRequestsID.remove(requestId);
  }
}
 
Example 19
Project: GitHub   File: ImagePipeline.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a DataSource supplier that will on get submit the request for execution and return a
 * DataSource representing the pending results of the task.
 *
 * @param imageRequest the request to submit (what to execute).
 * @param callerContext the caller context of the caller of data source supplier
 * @param requestLevel which level to look down until for the image
 * @return a DataSource representing pending results and completion of the request
 */
public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier(
    final ImageRequest imageRequest,
    final Object callerContext,
    final ImageRequest.RequestLevel requestLevel) {
  return new Supplier<DataSource<CloseableReference<CloseableImage>>>() {
    @Override
    public DataSource<CloseableReference<CloseableImage>> get() {
      return fetchDecodedImage(imageRequest, callerContext, requestLevel);
    }

    @Override
    public String toString() {
      return Objects.toStringHelper(this)
          .add("uri", imageRequest.getSourceUri())
          .toString();
    }
  };
}
 
Example 20
Project: GitHub   File: ImagePipeline.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a DataSource supplier that will on get submit the request for execution and return a
 * DataSource representing the pending results of the task.
 *
 * @param imageRequest the request to submit (what to execute).
 * @return a DataSource representing pending results and completion of the request
 */
public Supplier<DataSource<CloseableReference<PooledByteBuffer>>>
getEncodedImageDataSourceSupplier(
    final ImageRequest imageRequest,
    final Object callerContext) {
  return new Supplier<DataSource<CloseableReference<PooledByteBuffer>>>() {
    @Override
    public DataSource<CloseableReference<PooledByteBuffer>> get() {
      return fetchEncodedImage(imageRequest, callerContext);
    }

    @Override
    public String toString() {
      return Objects.toStringHelper(this)
          .add("uri", imageRequest.getSourceUri())
          .toString();
    }
  };
}
 
Example 21
Project: GitHub   File: ImagePipeline.java   Source Code and License 6 votes vote down vote up
/**
 * Submits a request for execution and returns a DataSource representing the pending decoded
 * image(s).
 * <p>The returned DataSource must be closed once the client has finished with it.
 *
 * @param imageRequest the request to submit
 * @param callerContext the caller context for image request
 * @param lowestPermittedRequestLevelOnSubmit the lowest request level permitted for image request
 * @return a DataSource representing the pending decoded image(s)
 */
public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage(
    ImageRequest imageRequest,
    Object callerContext,
    ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit) {
  try {
    Producer<CloseableReference<CloseableImage>> producerSequence =
        mProducerSequenceFactory.getDecodedImageProducerSequence(imageRequest);
    return submitFetchRequest(
        producerSequence,
        imageRequest,
        lowestPermittedRequestLevelOnSubmit,
        callerContext);
  } catch (Exception exception) {
    return DataSources.immediateFailedDataSource(exception);
  }
}
 
Example 22
Project: GitHub   File: ImagePipeline.java   Source Code and License 6 votes vote down vote up
/**
 * Submits a request for prefetching to the bitmap cache.
 *
 * <p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow
 * down images which are immediately required on screen.
 *
 * @param imageRequest the request to submit
 * @return a DataSource that can safely be ignored.
 */
public DataSource<Void> prefetchToBitmapCache(
    ImageRequest imageRequest,
    Object callerContext) {
  if (!mIsPrefetchEnabledSupplier.get()) {
    return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION);
  }
  try {
    Producer<Void> producerSequence = mSuppressBitmapPrefetchingSupplier.get()
        ? mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest)
        : mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(imageRequest);
    return submitPrefetchRequest(
        producerSequence,
        imageRequest,
        ImageRequest.RequestLevel.FULL_FETCH,
        callerContext,
        Priority.MEDIUM);
  } catch (Exception exception) {
    return DataSources.immediateFailedDataSource(exception);
  }
}
 
Example 23
Project: GitHub   File: ImagePipeline.java   Source Code and License 6 votes vote down vote up
/**
 * Submits a request for prefetching to the disk cache.
 *
 * <p> Beware that if your network fetcher doesn't support priorities prefetch requests may slow
 * down images which are immediately required on screen.
 *
 * @param imageRequest the request to submit
 * @param priority custom priority for the fetch
 * @return a DataSource that can safely be ignored.
 */
public DataSource<Void> prefetchToDiskCache(
    ImageRequest imageRequest,
    Object callerContext,
    Priority priority) {
  if (!mIsPrefetchEnabledSupplier.get()) {
    return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION);
  }
  try {
    Producer<Void> producerSequence =
        mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest);
    return submitPrefetchRequest(
        producerSequence,
        imageRequest,
        ImageRequest.RequestLevel.FULL_FETCH,
        callerContext,
        priority);
  } catch (Exception exception) {
    return DataSources.immediateFailedDataSource(exception);
  }
}
 
Example 24
Project: RNLearn_Project1   File: SystraceRequestListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onRequestStart(
    ImageRequest request,
    Object callerContext,
    String requestId,
    boolean isPrefetch) {
  if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) {
    return;
  }

  StringBuilder entryName = new StringBuilder();
  entryName.append("FRESCO_REQUEST_");
  entryName.append(request.getSourceUri().toString().replace(':', '_'));

  Pair<Integer,String> requestPair = Pair.create(mCurrentID, entryName.toString());
  Systrace.beginAsyncSection(
      Systrace.TRACE_TAG_REACT_FRESCO,
      requestPair.second,
      mCurrentID);
  mRequestsID.put(requestId, requestPair);
  mCurrentID++;
}
 
Example 25
Project: GitHub   File: BoxingFrescoLoader.java   Source Code and License 5 votes vote down vote up
@Override
public void displayRaw(@NonNull ImageView img, @NonNull String absPath, int width, int height,  IBoxingCallback callback) {
    absPath = "file://" + absPath;
    ImageRequestBuilder requestBuilder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(absPath));
    if (width > 0 && height > 0) {
        requestBuilder.setResizeOptions(new ResizeOptions(width, height));
    }
    ImageRequest request = requestBuilder.build();
    loadImage(request, img, callback);
}
 
Example 26
Project: GitHub   File: PipelineDraweeControllerBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public PipelineDraweeControllerBuilder setUri(@Nullable Uri uri) {
  if (uri == null) {
    return super.setImageRequest(null);
  }
  ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri)
      .setRotationOptions(RotationOptions.autoRotateAtRenderTime())
      .build();
  return super.setImageRequest(imageRequest);
}
 
Example 27
Project: GitHub   File: PipelineDraweeControllerBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public PipelineDraweeControllerBuilder setUri(@Nullable String uriString) {
  if (uriString == null || uriString.isEmpty()) {
    return super.setImageRequest(ImageRequest.fromUri(uriString));
  }
  return setUri(Uri.parse(uriString));
}
 
Example 28
Project: GitHub   File: PipelineDraweeControllerBuilder.java   Source Code and License 5 votes vote down vote up
@Override
protected DataSource<CloseableReference<CloseableImage>> getDataSourceForRequest(
    ImageRequest imageRequest,
    Object callerContext,
    CacheLevel cacheLevel) {
  return mImagePipeline.fetchDecodedImage(
      imageRequest,
      callerContext,
      convertCacheLevelToRequestLevel(cacheLevel));
}
 
Example 29
Project: GitHub   File: PipelineDraweeControllerBuilder.java   Source Code and License 5 votes vote down vote up
public static ImageRequest.RequestLevel convertCacheLevelToRequestLevel(
    AbstractDraweeControllerBuilder.CacheLevel cacheLevel) {
  switch (cacheLevel) {
    case FULL_FETCH:
      return ImageRequest.RequestLevel.FULL_FETCH;
    case DISK_CACHE:
      return ImageRequest.RequestLevel.DISK_CACHE;
    case BITMAP_MEMORY_CACHE:
      return ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE;
    default:
      throw new RuntimeException("Cache level" + cacheLevel + "is not supported. ");
  }
}
 
Example 30
Project: GitHub   File: ImagePipelineConfigTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testImageRequestWhenChanged() {
  ImagePipelineConfig.resetDefaultRequestConfig();
  ImagePipelineConfig.getDefaultImageRequestConfig().setProgressiveRenderingEnabled(true);
  final ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(mUri).build();
  assertTrue(imageRequest.getProgressiveRenderingEnabled());
}
 
Example 31
Project: cardinalsSample   File: FrescoManager.java   Source Code and License 5 votes vote down vote up
/**
 * @param view View
 * @param url  网络路径或者本地路径
 */

public void display(SimpleDraweeView view, String url) {
    if (!TextUtils.isEmpty(url)) {
        Uri uri;
        if (URLUtil.isNetworkUrl(url)) {
            uri = Uri.parse(url);
        } else {
            uri = Uri.fromFile(new File(url));
        }
        ImageRequest request = ImageRequestBuilder
                .newBuilderWithSource(uri)
                .setProgressiveRenderingEnabled(true)
                .setLocalThumbnailPreviewsEnabled(true)
                .setRotationOptions(RotationOptions.autoRotateAtRenderTime())
                .build();

        controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setTapToRetryEnabled(true)
                .setOldController(view.getController())
                .build();
        view.setController(controller);

    }

}
 
Example 32
Project: RNLearn_Project1   File: SystraceRequestListener.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequestSuccess(ImageRequest request, String requestId, boolean isPrefetch) {
  if (!Systrace.isTracing(Systrace.TRACE_TAG_REACT_FRESCO)) {
    return;
  }

  if (mRequestsID.containsKey(requestId)) {
    Pair<Integer, String> entry = mRequestsID.get(requestId);
    Systrace.endAsyncSection(
        Systrace.TRACE_TAG_REACT_FRESCO,
        entry.second,
        entry.first);
    mRequestsID.remove(requestId);
  }
}
 
Example 33
Project: GitHub   File: ForwardingRequestListener.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequestStart(
    ImageRequest request, Object callerContext, String requestId, boolean isPrefetch) {
  final int numberOfListeners = mRequestListeners.size();
  for (int i = 0; i < numberOfListeners; ++i) {
    RequestListener listener = mRequestListeners.get(i);
    try {
      listener.onRequestStart(request, callerContext, requestId, isPrefetch);
    } catch (Exception exception) {
      // Don't punish the other listeners if we're given a bad one.
      onException("InternalListener exception in onRequestStart", exception);
    }
  }
}
 
Example 34
Project: GitHub   File: ForwardingRequestListener.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequestSuccess(ImageRequest request, String requestId, boolean isPrefetch) {
  final int numberOfListeners = mRequestListeners.size();
  for (int i = 0; i < numberOfListeners; ++i) {
    RequestListener listener = mRequestListeners.get(i);
    try {
      listener.onRequestSuccess(request, requestId, isPrefetch);
    } catch (Exception exception) {
      // Don't punish the other listeners if we're given a bad one.
      onException("InternalListener exception in onRequestSuccess", exception);
    }
  }
}
 
Example 35
Project: tumbviewer   File: FrescoUtils.java   Source Code and License 5 votes vote down vote up
public static void save(Uri uri, String action) {
    ImageRequest request = ImageRequest.fromUri(uri);
    ImagePipeline pipeline = Fresco.getImagePipeline();
    DataSource<CloseableReference<PooledByteBuffer>> dataSource =
            pipeline.fetchEncodedImage(request, null);

    ImageSubscriber dataSubscriber = new ImageSubscriber(uri, action);

    dataSource.subscribe(dataSubscriber,
            ExpressApplication.getApplication().getImagePipelineConfig()
                    .getExecutorSupplier().forLocalStorageWrite());
}
 
Example 36
Project: GitHub   File: RepeatedPostprocessorProducerTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  mTestExecutorService = new TestExecutorService(new FakeClock());
  mPostprocessorProducer =
      new PostprocessorProducer(
          mInputProducer,
          mPlatformBitmapFactory,
          mTestExecutorService);
  mProducerContext =
      new SettableProducerContext(
          mImageRequest,
          mRequestId,
          mProducerListener,
          mock(Object.class),
          ImageRequest.RequestLevel.FULL_FETCH,
          false /* isPrefetch */,
          false /* isIntermediateResultExpected */,
          Priority.MEDIUM);
  when(mImageRequest.getPostprocessor()).thenReturn(mPostprocessor);
  mResults = new ArrayList<>();
  when(mPostprocessor.getName()).thenReturn(POSTPROCESSOR_NAME);
  when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true);
  doAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          mResults.add(
              ((CloseableReference<CloseableImage>) invocation.getArguments()[0]).clone());
          return null;
        }
      }
  ).when(mConsumer).onNewResult(any(CloseableReference.class), anyInt());
  mInOrder = inOrder(mPostprocessor, mProducerListener, mConsumer);
}
 
Example 37
Project: RNLearn_Project1   File: FrescoBasedReactTextInlineImageSpan.java   Source Code and License 5 votes vote down vote up
@Override
public void draw(
    Canvas canvas,
    CharSequence text,
    int start,
    int end,
    float x,
    int top,
    int y,
    int bottom,
    Paint paint) {
  if (mDrawable == null) {
    ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(mUri);
    ImageRequest imageRequest = ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, mHeaders);

    DraweeController draweeController = mDraweeControllerBuilder
        .reset()
        .setOldController(mDraweeHolder.getController())
        .setCallerContext(mCallerContext)
        .setImageRequest(imageRequest)
        .build();
    mDraweeHolder.setController(draweeController);

    mDrawable = mDraweeHolder.getTopLevelDrawable();
    mDrawable.setBounds(0, 0, mWidth, mHeight);
    mDrawable.setCallback(mTextView);
  }

  // NOTE: This drawing code is copied from DynamicDrawableSpan

  canvas.save();

  // Align to baseline by default
  int transY = y - mDrawable.getBounds().bottom;

  canvas.translate(x, transY);
  mDrawable.draw(canvas);
  canvas.restore();
}
 
Example 38
Project: GitHub   File: DefaultCacheKeyFactory.java   Source Code and License 5 votes vote down vote up
@Override
public CacheKey getBitmapCacheKey(ImageRequest request, Object callerContext) {
  return new BitmapMemoryCacheKey(
      getCacheKeySourceUri(request.getSourceUri()).toString(),
      request.getResizeOptions(),
      request.getRotationOptions(),
      request.getImageDecodeOptions(),
      null,
      null,
      callerContext);
}
 
Example 39
Project: GitHub   File: ImagePipeline.java   Source Code and License 5 votes vote down vote up
private <T> DataSource<CloseableReference<T>> submitFetchRequest(
    Producer<CloseableReference<T>> producerSequence,
    ImageRequest imageRequest,
    ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit,
    Object callerContext) {
  final RequestListener requestListener = getRequestListenerForRequest(imageRequest);

  try {
    ImageRequest.RequestLevel lowestPermittedRequestLevel =
        ImageRequest.RequestLevel.getMax(
            imageRequest.getLowestPermittedRequestLevel(),
            lowestPermittedRequestLevelOnSubmit);
    SettableProducerContext settableProducerContext = new SettableProducerContext(
        imageRequest,
        generateUniqueFutureId(),
        requestListener,
        callerContext,
        lowestPermittedRequestLevel,
      /* isPrefetch */ false,
        imageRequest.getProgressiveRenderingEnabled() ||
            imageRequest.getMediaVariations() != null ||
            !UriUtil.isNetworkUri(imageRequest.getSourceUri()),
        imageRequest.getPriority());
    return CloseableProducerToDataSourceAdapter.create(
        producerSequence,
        settableProducerContext,
        requestListener);
  } catch (Exception exception) {
    return DataSources.immediateFailedDataSource(exception);
  }
}
 
Example 40
Project: GitHub   File: DefaultCacheKeyFactory.java   Source Code and License 5 votes vote down vote up
@Override
public CacheKey getEncodedCacheKey(
    ImageRequest request,
    Uri sourceUri,
    @Nullable Object callerContext) {
  return new SimpleCacheKey(getCacheKeySourceUri(sourceUri).toString());
}