如果您对com.facebook.imagepipeline.image.EncodedImage的实例源码和facebook源代码感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解com.fac
如果您对com.facebook.imagepipeline.image.EncodedImage的实例源码和facebook源代码感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解com.facebook.imagepipeline.image.EncodedImage的实例源码的各种细节,并对facebook源代码进行深入的分析,此外还有关于com.facebook.animated.webp.WebPImage的实例源码、com.facebook.imagepipeline.animated.base.AnimatedDrawable的实例源码、com.facebook.imagepipeline.animated.base.AnimatedImageFrame的实例源码、com.facebook.imagepipeline.animated.base.AnimatedImageResult的实例源码的实用技巧。
本文目录一览:- com.facebook.imagepipeline.image.EncodedImage的实例源码(facebook源代码)
- com.facebook.animated.webp.WebPImage的实例源码
- com.facebook.imagepipeline.animated.base.AnimatedDrawable的实例源码
- com.facebook.imagepipeline.animated.base.AnimatedImageFrame的实例源码
- com.facebook.imagepipeline.animated.base.AnimatedImageResult的实例源码
com.facebook.imagepipeline.image.EncodedImage的实例源码(facebook源代码)
/** * Decodes a GIF into a CloseableImage. * @param encodedImage encoded image (native byte array holding the encoded bytes and Meta data) * @param options the options for the decode * @param bitmapConfig the Bitmap.Config used to generate the output bitmaps * @return a {@link CloseableImage} for the GIF image */ public CloseableImage decodeGif( final EncodedImage encodedImage,final ImageDecodeOptions options,final Bitmap.Config bitmapConfig) { if (sgifAnimatedimagedecoder == null) { throw new UnsupportedOperationException("To encode animated gif please add the dependency " + "to the animated-gif module"); } final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef(); Preconditions.checkNotNull(bytesRef); try { final PooledByteBuffer input = bytesRef.get(); AnimatedImage gifImage = sgifAnimatedimagedecoder.decode(input.getNativePtr(),input.size()); return getCloseableImage(options,gifImage,bitmapConfig); } finally { CloseableReference.closeSafely(bytesRef); } }
/** * Decode a WebP into a CloseableImage. * @param encodedImage encoded image (native byte array holding the encoded bytes and Meta data) * @param options the options for the decode * @param bitmapConfig the Bitmap.Config used to generate the output bitmaps * @return a {@link CloseableImage} for the WebP image */ public CloseableImage decodeWebP( final EncodedImage encodedImage,final Bitmap.Config bitmapConfig) { if (sWebpAnimatedimagedecoder == null) { throw new UnsupportedOperationException("To encode animated webp please add the dependency " + "to the animated-webp module"); } final CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef(); Preconditions.checkNotNull(bytesRef); try { final PooledByteBuffer input = bytesRef.get(); AnimatedImage webPImage = sWebpAnimatedimagedecoder.decode( input.getNativePtr(),input.size()); return getCloseableImage(options,webPImage,bitmapConfig); } finally { CloseableReference.closeSafely(bytesRef); } }
@Test public void testSmallImagediskCacheGetSuccessful() { when(mImageRequest.getCacheChoice()).thenReturn(ImageRequest.CacheChoice.SMALL); setupdiskCacheGetSuccess(mSmallImageBuffereddiskCache); 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("true",resultMap.get(diskCacheReadProducer.EXTRA_CACHED_VALUE_FOUND)); assertEquals( "0",resultMap.get(diskCacheReadProducer.ENCODED_IMAGE_SIZE)); verify(mProducerListener).onUltimateProducerReached(mRequestId,PRODUCER_NAME,true); Assert.assertFalse(EncodedImage.isValid(mFinalEncodedImage)); }
@Override protected void onNewResultImpl(@Nullable EncodedImage newResult,@Status int status) { // try to determine if the last result should be transformed if (mShouldTranscodeWhenFinished == TriState.UNSET && newResult != null) { mShouldTranscodeWhenFinished = shouldTranscode(newResult); } // just propagate result if it shouldn't be transformed if (mShouldTranscodeWhenFinished == TriState.NO) { getConsumer().onNewResult(newResult,status); return; } if (isLast(status)) { if (mShouldTranscodeWhenFinished == TriState.YES && newResult != null) { transcodeLastResult(newResult,getConsumer(),mContext); } else { getConsumer().onNewResult(newResult,status); } } }
/** * bitmap cache get -> * background thread hand-off -> bitmap cache -> decode -> resize and rotate -> (webp transcode) * -> data fetch. */ private synchronized Producer<CloseableReference<CloseableImage>> getDataFetchSequence() { if (mDataFetchSequence == null) { Producer<EncodedImage> inputProducer = mProducerFactory.newDataFetchProducer(); if (WebpSupportStatus.sIsWebpSupportrequired && (!mWebpSupportEnabled || WebpSupportStatus.sWebpBitmapFactory == null)) { inputProducer = mProducerFactory.newWebpTranscodeProducer(inputProducer); } inputProducer = mProducerFactory.newAddImageTransformMetaDataProducer(inputProducer); inputProducer = mProducerFactory.newResizeAndRotateProducer( inputProducer,true,mUseDownsamplingRatio); mDataFetchSequence = newBitmapCacheGetToDecodeSequence(inputProducer); } return mDataFetchSequence; }
@Test public void testFirstProducerResultNotGoodEnough() { EncodedImage firstProducerEncodedImage = new EncodedImage( mFirstProducerFinalResult.getByteBufferRef()); firstProducerEncodedImage.setRotationAngle(-1); firstProducerEncodedImage.setWidth(WIDTH / 2); firstProducerEncodedImage.setHeight(HEIGHT / 2); mFirstProducerConsumer.onNewResult(firstProducerEncodedImage,Consumer.IS_LAST); verify(mConsumer).onNewResult(firstProducerEncodedImage,Consumer.NO_FLAGS); EncodedImage intermediateEncodedImage = new EncodedImage( mIntermediateResult.getByteBufferRef()); intermediateEncodedImage.setRotationAngle(-1); intermediateEncodedImage.setWidth(WIDTH / 2); intermediateEncodedImage.setHeight(HEIGHT / 2); mSecondProducerConsumer.onNewResult(intermediateEncodedImage,Consumer.NO_FLAGS); verify(mConsumer).onNewResult(intermediateEncodedImage,Consumer.NO_FLAGS); EncodedImage secondProducerEncodedImage = new EncodedImage( mSecondProducerFinalResult.getByteBufferRef()); secondProducerEncodedImage.setRotationAngle(-1); secondProducerEncodedImage.setWidth(WIDTH / 2); secondProducerEncodedImage.setHeight(HEIGHT / 2); mSecondProducerConsumer.onNewResult(secondProducerEncodedImage,Consumer.IS_LAST); verify(mConsumer).onNewResult(secondProducerEncodedImage,Consumer.IS_LAST); }
@Test public void testEncodedMemoryCacheGetNotFoundInputProducerSuccess() { setupEncodedMemoryCacheGetNotFound(); setupInputProducerStreamingSuccess(); mEncodedMemoryCacheProducer.produceResults(mConsumer,mProducerContext); verify(mMemoryCache,never()).cache(mCacheKey,mIntermediateImageReference); ArgumentCaptor<CloseableReference> argumentCaptor = ArgumentCaptor.forClass(CloseableReference.class); verify(mMemoryCache).cache(eq(mCacheKey),argumentCaptor.capture()); CloseableReference<PooledByteBuffer> capturedRef = (CloseableReference<PooledByteBuffer>) argumentCaptor.getValue(); Assert.assertSame( mFinalImageReference.getUnderlyingReferenceTestOnly(),capturedRef.getUnderlyingReferenceTestOnly()); verify(mConsumer).onNewResult(mIntermediateEncodedImage,Consumer.NO_FLAGS); verify(mConsumer).onNewResult(mFinalEncodedImage,Consumer.IS_LAST); Assert.assertTrue(EncodedImage.isValid(mFinalEncodedImageClone)); verify(mProducerListener).onProducerStart(mRequestId,PRODUCER_NAME); Map<String,String> extraMap = ImmutableMap.of(EncodedMemoryCacheProducer.EXTRA_CACHED_VALUE_FOUND,"false"); verify(mProducerListener).onProducerFinishWithSuccess(mRequestId,extraMap); verify(mProducerListener,never()) .onUltimateProducerReached(anyString(),anyString(),anyBoolean()); }
/** * Creates a bitmap from encoded bytes. * * @param encodedImage the encoded image with reference to the encoded bytes * @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded * Bitmap * @param regionToDecode optional image region to decode. currently not supported. * @return the bitmap * @throws TooManyBitmapsException if the pool is full * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated */ @Override public CloseableReference<Bitmap> decodeFromEncodedImage( final EncodedImage encodedImage,Bitmap.Config bitmapConfig,@Nullable Rect regionToDecode) { BitmapFactory.Options options = getBitmapFactoryOptions( encodedImage.getSampleSize(),bitmapConfig); CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef(); Preconditions.checkNotNull(bytesRef); try { Bitmap bitmap = decodeByteArrayAsPurgeable(bytesRef,options); return pinBitmap(bitmap); } finally { CloseableReference.closeSafely(bytesRef); } }
/** * bitmap cache get -> * background thread hand-off -> multiplex -> bitmap cache -> decode -> * branch on separate images * -> thumbnail resize and rotate -> thumbnail branch * -> local content thumbnail creation * -> exif thumbnail creation * -> local image resize and rotate -> add Meta data producer -> multiplex -> encoded cache -> * (webp transcode) -> local content uri fetch. */ private synchronized Producer<CloseableReference<CloseableImage>> getLocalContentUriFetchSequence() { if (mLocalContentUriFetchSequence == null) { LocalContentUriFetchProducer localContentUriFetchProducer = mProducerFactory.newLocalContentUriFetchProducer(); ThumbnailProducer<EncodedImage>[] thumbnailProducers = new ThumbnailProducer[2]; thumbnailProducers[0] = mProducerFactory.newLocalContentUriThumbnailFetchProducer(); thumbnailProducers[1] = mProducerFactory.newLocalExifThumbnailProducer(); mLocalContentUriFetchSequence = newBitmapCacheGetToLocalTransformSequence( localContentUriFetchProducer,thumbnailProducers); } return mLocalContentUriFetchSequence; }
/** * Options returned by this method are configured with mDecodeBuffer which is GuardedBy("this") */ private static BitmapFactory.Options getDecodeOptionsForStream( EncodedImage encodedImage,Bitmap.Config bitmapConfig) { final BitmapFactory.Options options = new BitmapFactory.Options(); // Sample size should ONLY be different than 1 when downsampling is enabled in the pipeline options.inSampleSize = encodedImage.getSampleSize(); options.inJustDecodeBounds = true; // fill outWidth and outHeight BitmapFactory.decodeStream(encodedImage.getInputStream(),null,options); if (options.outWidth == -1 || options.outHeight == -1) { throw new IllegalArgumentException(); } options.inJustDecodeBounds = false; options.inDither = true; options.inPreferredConfig = bitmapConfig; options.inMutable = true; return options; }
/** * Decodes image. * * @param encodedImage input image (encoded bytes plus Meta data) * @param length if image type supports decoding incomplete image then determines where the image * data should be cut for decoding. * @param qualityInfo quality information for the image * @param options options that cange decode behavior */ @Override public CloseableImage decode( final EncodedImage encodedImage,final int length,final QualityInfo qualityInfo,final ImageDecodeOptions options) { if (options.customimagedecoder != null) { return options.customimagedecoder.decode(encodedImage,length,qualityInfo,options); } ImageFormat imageFormat = encodedImage.getimageFormat(); if (imageFormat == null || imageFormat == ImageFormat.UNKNowN) { imageFormat = ImageFormatChecker.getimageFormat_WrapIOException( encodedImage.getInputStream()); encodedImage.setimageFormat(imageFormat); } if (mCustomDecoders != null) { imagedecoder decoder = mCustomDecoders.get(imageFormat); if (decoder != null) { return decoder.decode(encodedImage,options); } } return mDefaultDecoder.decode(encodedImage,options); }
/** * Determine if an valid entry for the key exists in the staging area. */ public synchronized boolean containsKey(CacheKey key) { Preconditions.checkNotNull(key); if (!mMap.containsKey(key)) { return false; } EncodedImage storedEncodedImage = mMap.get(key); synchronized (storedEncodedImage) { if (!EncodedImage.isValid(storedEncodedImage)) { // Reference is not valid,this means that someone cleared reference while it was still in // use. Log error // Todo: 3697790 mMap.remove(key); FLog.w( TAG,"Found closed reference %d for key %s (%d)",System.identityHashCode(storedEncodedImage),key.getUriString(),System.identityHashCode(key)); return false; } return true; } }
/** * Performs key-value loop up in staging area and file cache. * Any error manifests itself as a miss,i.e. returns false. * @param key * @return true if the image is found in staging area or File cache,false if not found */ private boolean checkInStagingAreaAndFileCache(final CacheKey key) { EncodedImage result = mStagingArea.get(key); if (result != null) { result.close(); FLog.v(TAG,"Found image for %s in staging area",key.getUriString()); mImageCacheStatsTracker.onStagingAreaHit(key); return true; } else { FLog.v(TAG,"Did not find image for %s in staging area",key.getUriString()); mImageCacheStatsTracker.onStagingAreaMiss(); try { return mFileCache.hasKey(key); } catch (Exception exception) { return false; } } }
private void mockThumbnailFile() throws Exception { powermockito.whenNew(File.class) .withArguments(THUMBNAIL_FILE_NAME) .thenReturn(mThumbnailFile); when(mThumbnailFile.exists()).thenReturn(true); when(mThumbnailFile.length()).thenReturn(THUMBNAIL_FILE_SIZE); powermockito.whenNew(FileInputStream.class) .withArguments(THUMBNAIL_FILE_NAME) .thenReturn(mock(FileInputStream.class)); EncodedImage encodedImage = mock(EncodedImage.class); when(encodedImage.getSize()).thenReturn((int) THUMBNAIL_FILE_SIZE); powermockito.whenNew(EncodedImage.class) .withAnyArguments() .thenReturn(encodedImage); }
@Override public void produceResults(Consumer<EncodedImage> consumer,ProducerContext context) { context.getListener() .onProducerStart(context.getId(),PRODUCER_NAME); final FetchState fetchState = mNetworkFetcher.createFetchState(consumer,context); mNetworkFetcher.fetch( fetchState,new NetworkFetcher.Callback() { @Override public void onResponse(InputStream response,int responseLength) throws IOException { NetworkFetchProducer.this.onResponse(fetchState,response,responseLength); } @Override public void onFailure(Throwable throwable) { NetworkFetchProducer.this.onFailure(fetchState,throwable); } @Override public void onCancellation() { NetworkFetchProducer.this.onCancellation(fetchState); } }); }
@Test public void testOnNewResultNotLast_DimensionsNotFound() { int rotationAngle = 180; int orientation = 1; when(ImageFormatChecker.getimageFormat_WrapIOException(any(InputStream.class))) .thenReturn(DefaultimageFormats.JPEG); when(JfifUtil.getAutoRotateAngleFromOrientation(orientation)).thenReturn(rotationAngle); when(JfifUtil.getorientation(any(InputStream.class))).thenReturn(orientation); when(BitmapUtil.decodeDimensions(any(InputStream.class))).thenReturn(null); mAddMetaDataConsumer.onNewResult(mIntermediateResult,Consumer.NO_FLAGS); ArgumentCaptor<EncodedImage> argumentCaptor = ArgumentCaptor.forClass(EncodedImage.class); verify(mConsumer).onNewResult(argumentCaptor.capture(),eq(Consumer.NO_FLAGS)); EncodedImage encodedImage = argumentCaptor.getValue(); assertTrue(EncodedImage.isValid(encodedImage)); assertEquals(-1,encodedImage.getRotationAngle()); assertEquals(-1,encodedImage.getWidth()); assertEquals(-1,encodedImage.getHeight()); }
@Test public void testDoesNottransformIfImageRotationAngleUnkown() { whenResizingEnabled(); whenRequestSpecificRotation(Rotationoptions.NO_ROTATION); provideIntermediateResult( DefaultimageFormats.JPEG,800,EncodedImage.UNKNowN_ROTATION_ANGLE,ExifInterface.ORIENTATION_UNDEFINED); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult( DefaultimageFormats.JPEG,ExifInterface.ORIENTATION_UNDEFINED); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); }
/** * background-thread hand-off -> multiplex -> encoded cache -> * disk cache -> (webp transcode) -> local file fetch */ private synchronized Producer<EncodedImage> getBackgroundLocalFileFetchToEncodeMemorySequence() { if (mBackgroundLocalFileFetchToEncodedMemorySequence == null) { final LocalFileFetchProducer localFileFetchProducer = mProducerFactory.newLocalFileFetchProducer(); final Producer<EncodedImage> toEncodedMultiplexProducer = newEncodedCacheMultiplexToTranscodeSequence(localFileFetchProducer); mBackgroundLocalFileFetchToEncodedMemorySequence = mProducerFactory.newBackgroundThreadHandoffProducer( toEncodedMultiplexProducer,mThreadHandoffProducerQueue); } return mBackgroundLocalFileFetchToEncodedMemorySequence; }
private void verifyInputProducerProduceResultsWithNewConsumer(boolean allowIntermediateResult) { verify(mInputProducer) .produceResults(mConsumerCaptor.capture(),mProducerContextCaptor.capture()); Consumer<EncodedImage> consumer = mConsumerCaptor.getValue(); assertthat(consumer).isinstanceOf(MediaVariationsConsumer.class); assertthat(((MediaVariationsConsumer) consumer).getConsumer()).isSameAs(mConsumer); SettableProducerContext referenceContext = new SettableProducerContext(mProducerContext); referenceContext.setIsIntermediateResultExpected(allowIntermediateResult); ProducerContext capturedContext = mProducerContextCaptor.getValue(); assertEquals(referenceContext.getCallerContext(),capturedContext.getCallerContext()); assertEquals(referenceContext.getId(),capturedContext.getId()); assertEquals(referenceContext.getimageRequest(),capturedContext.getimageRequest()); assertEquals(referenceContext.getListener(),capturedContext.getListener()); assertEquals( referenceContext.getLowestPermittedRequestLevel(),capturedContext.getLowestPermittedRequestLevel()); assertEquals(referenceContext.getPriority(),capturedContext.getPriority()); assertEquals( referenceContext.isIntermediateResultExpected(),capturedContext.isIntermediateResultExpected()); }
@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); } }
private @Nullable EncodedImage getCameraimage(Uri uri) throws IOException { Cursor cursor = mContentResolver.query(uri,PROJECTION,null); if (cursor == null) { return null; } try { if (cursor.getCount() == 0) { return null; } cursor.movetoFirst(); final String pathname = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)); if (pathname != null) { return getEncodedImage(new FileInputStream(pathname),getLength(pathname)); } } finally { cursor.close(); } return null; }
@Test public void testSchedule_Last_Queued() { mJobScheduler.updateJob(fakeEncodedImage(),Consumer.IS_LAST); assertTrue(mJobScheduler.scheduleJob()); EncodedImage encodedImage2 = fakeEncodedImage(); mJobScheduler.updateJob(encodedImage2,Consumer.IS_LAST); assertEquals(JobScheduler.JobState.QUEUED,mJobScheduler.mJobState); assertTrue(mJobScheduler.scheduleJob()); assertEquals(0,mTestscheduledexecutorservice.getPendingCount()); assertEquals(1,mTestExecutorService.getPendingCount()); assertEquals(0,mTestJobRunnable.jobs.size()); mFakeClockForTime.incrementBy(1234); mFakeClockForWorker.incrementBy(1234); mFakeClockForScheduled.incrementBy(1234); assertEquals(1,mTestJobRunnable.jobs.size()); assertJobsEqual(mTestJobRunnable.jobs.get(0),encodedImage2,Consumer.IS_LAST); }
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); }
private static boolean shouldProcess(EncodedImage encodedImage,@Consumer.Status int status) { // the last result should always be processed,whereas // an intermediate result should be processed only if valid return BaseConsumer.isLast(status) || BaseConsumer.statusHasFlag(status,Consumer.IS_PLACEHOLDER) || EncodedImage.isValid(encodedImage); }
@Override public imagedecoder getGifDecoder(final Bitmap.Config bitmapConfig) { return new imagedecoder() { @Override public CloseableImage decode( EncodedImage encodedImage,int length,QualityInfo qualityInfo,ImageDecodeOptions options) { return getAnimatedImageFactory().decodeGif(encodedImage,options,bitmapConfig); } }; }
private void startInputProducer( Consumer<EncodedImage> consumerOfPartialdiskCacheProducer,ProducerContext producerContext,CacheKey partialImageCacheKey,@Nullable EncodedImage partialResultFromCache) { Consumer<EncodedImage> consumer = new PartialdiskCacheConsumer( consumerOfPartialdiskCacheProducer,mDefaultBuffereddiskCache,partialImageCacheKey,mPooledByteBufferFactory,mByteArrayPool,partialResultFromCache); mInputProducer.produceResults(consumer,producerContext); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); mEncodedMemoryCacheProducer = new EncodedMemoryCacheProducer(mMemoryCache,mCacheKeyFactory,mInputProducer); mPooledByteBuffer1 = mock(PooledByteBuffer.class); mPooledByteBuffer2 = mock(PooledByteBuffer.class); mFinalImageReference = CloseableReference.of(mPooledByteBuffer1); mIntermediateImageReference = CloseableReference.of(mPooledByteBuffer2); mFinalImageReferenceClone = mFinalImageReference.clone(); mFinalEncodedImage = new EncodedImage(mFinalImageReference); mIntermediateEncodedImage = new EncodedImage(mIntermediateImageReference); mFinalEncodedImageClone = new EncodedImage(mFinalImageReferenceClone); List<CacheKey> list = new ArrayList<>(); list.add(new SimpleCacheKey("http://dummy.uri")); mCacheKey = new MultiCacheKey(list); when(mCacheKeyFactory.getEncodedCacheKey(mImageRequest,mCallerContext)).thenReturn(mCacheKey); when(mMemoryCache.cache(mCacheKey,mFinalImageReference)).thenReturn(mFinalImageReferenceClone); when(mProducerContext.getimageRequest()).thenReturn(mImageRequest); when(mProducerContext.getCallerContext()).thenReturn(mCallerContext); when(mProducerContext.getListener()).thenReturn(mProducerListener); when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true); when(mProducerContext.getId()).thenReturn(mRequestId); when(mProducerContext.getLowestPermittedRequestLevel()) .thenReturn(ImageRequest.RequestLevel.FULL_FETCH); }
@Test public void testimageWithInsufficientHeightWhennoresizeOptions() { for (int rotation = 0; rotation < 360; rotation += 90) { EncodedImage mockImage = mockImage( BIG_ENOUGH_SIZE_FOR_NO_RESIZE_OPTIONS,BIG_ENOUGH_SIZE_FOR_NO_RESIZE_OPTIONS - 1,rotation); assertFalse(ThumbnailSizeChecker.isImageBigEnough(mockImage,null)); } }
/** * encoded cache multiplex -> encoded cache -> (disk cache) -> (webp transcode) * @param inputProducer producer providing the input to the transcode * @return encoded cache multiplex to webp transcode sequence */ private Producer<EncodedImage> newEncodedCacheMultiplexToTranscodeSequence( Producer<EncodedImage> inputProducer) { if (WebpSupportStatus.sIsWebpSupportrequired && (!mWebpSupportEnabled || WebpSupportStatus.sWebpBitmapFactory == null)) { inputProducer = mProducerFactory.newWebpTranscodeProducer(inputProducer); } inputProducer = newdiskCacheSequence(inputProducer); EncodedMemoryCacheProducer encodedMemoryCacheProducer = mProducerFactory.newEncodedMemoryCacheProducer(inputProducer); return mProducerFactory.newEncodedCacheKeyMultiplexProducer(encodedMemoryCacheProducer); }
/** * Clears the currently set job. * * <p> In case the currently set job has been scheduled but not started yet,the job won't be * executed. */ public void clearJob() { EncodedImage oldEncodedImage; synchronized (this) { oldEncodedImage = mEncodedImage; mEncodedImage = null; mStatus = 0; } EncodedImage.closeSafely(oldEncodedImage); }
@Test public void testClear() throws Exception { EncodedImage encodedImage = fakeEncodedImage(); mJobScheduler.updateJob(encodedImage,Consumer.IS_LAST); mJobScheduler.clearJob(); assertEquals(null,mJobScheduler.mEncodedImage); encodedImage.close(); assertNull(encodedImage.getByteBufferRef()); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mExecutor = new TestExecutorService(new FakeClock()); mLocalContentUriFetchProducer = new LocalContentUriFetchProducer( mExecutor,mContentResolver ); mContentUri = Uri.fromFile(mock(File.class)); mProducerContext = new SettableProducerContext( mImageRequest,mRequestId,mProducerListener,mock(Object.class),ImageRequest.RequestLevel.FULL_FETCH,false,Priority.MEDIUM); when(mImageRequest.getSourceUri()).thenReturn(mContentUri); doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { mCapturedEncodedImage = EncodedImage.cloneOrNull((EncodedImage) invocation.getArguments()[0]); return null; } }) .when(mConsumer) .onNewResult(notNull(EncodedImage.class),anyInt()); }
@Override public void saveCachedVariant( String mediaId,ImageRequest.CacheChoice cacheChoice,CacheKey cacheKey,EncodedImage encodedImage) { // no-op }
private static EncodedImage mockEncodedImage(int width,int height,int rotationAngle) { EncodedImage mockImage = mock(EncodedImage.class); when(mockImage.getWidth()).thenReturn(width); when(mockImage.getHeight()).thenReturn(height); when(mockImage.getRotationAngle()).thenReturn(rotationAngle); return mockImage; }
/** * Removes key-value from the StagingArea. Both key and value must match. * @param key * @param encodedImage value corresponding to key * @return true if item was removed */ public synchronized boolean remove(final CacheKey key,final EncodedImage encodedImage) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(encodedImage); Preconditions.checkArgument(EncodedImage.isValid(encodedImage)); final EncodedImage oldValue = mMap.get(key); if (oldValue == null) { return false; } CloseableReference<PooledByteBuffer> oldRef = oldValue.getByteBufferRef(); CloseableReference<PooledByteBuffer> ref = encodedImage.getByteBufferRef(); try { if (oldRef == null || ref == null || oldRef.get() != ref.get()) { return false; } mMap.remove(key); } finally { CloseableReference.closeSafely(ref); CloseableReference.closeSafely(oldRef); EncodedImage.closeSafely(oldValue); } logStats(); return true; }
public WebpTranscodeConsumer( final Consumer<EncodedImage> consumer,final ProducerContext context) { super(consumer); mContext = context; mShouldTranscodeWhenFinished = TriState.UNSET; }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mCloseableReference = CloseableReference.of(mPooledByteBuffer); mEncodedImage = new EncodedImage(mCloseableReference); List<CacheKey> keys = new ArrayList<>(); keys.add(new SimpleCacheKey("http://test.uri")); keys.add(new SimpleCacheKey("http://tyrone.uri")); keys.add(new SimpleCacheKey("http://ian.uri")); mCacheKey = new MultiCacheKey(keys); mIsCancelled = new AtomicBoolean(false); FakeClock fakeClock = new FakeClock(); mReadPriorityExecutor = new TestExecutorService(fakeClock); mWritePriorityExecutor = new TestExecutorService(fakeClock); when(mBinaryResource.openStream()).thenReturn(mInputStream); when(mBinaryResource.size()).thenReturn(123L); when(mByteBufferFactory.newByteBuffer(same(mInputStream),eq(123))) .thenReturn(mPooledByteBuffer); mockStatic(StagingArea.class); when(StagingArea.getInstance()).thenReturn(mStagingArea); mBuffereddiskCache = new BuffereddiskCache( mFileCache,mByteBufferFactory,mPooledByteStreams,mReadPriorityExecutor,mWritePriorityExecutor,mImageCacheStatsTracker); }
private void assertConsumerReceivesImage() { ArgumentCaptor<EncodedImage> resultCaptor = ArgumentCaptor.forClass(EncodedImage.class); verify(mConsumer).onNewResult(resultCaptor.capture(),eq(Consumer.IS_LAST)); assertNotNull(resultCaptor.getValue()); assertEquals(THUMBNAIL_FILE_SIZE,resultCaptor.getValue().getSize()); verifyNoMoreInteractions(mConsumer); }
public ResizeAndRotateProducer( Executor executor,PooledByteBufferFactory pooledByteBufferFactory,boolean resizingEnabled,Producer<EncodedImage> inputProducer,boolean useDownsamplingRatio) { mExecutor = Preconditions.checkNotNull(executor); mPooledByteBufferFactory = Preconditions.checkNotNull(pooledByteBufferFactory); mResizingEnabled = resizingEnabled; mInputProducer = Preconditions.checkNotNull(inputProducer); mUseDownsamplingRatio = useDownsamplingRatio; }
public EncodedMemoryCacheProducer newEncodedMemoryCacheProducer( Producer<EncodedImage> inputProducer) { return new EncodedMemoryCacheProducer( mEncodedMemoryCache,inputProducer); }
com.facebook.animated.webp.WebPImage的实例源码
@Before public void setup() { powermockito.mockStatic(WebPImage.class); mWebPImageMock = mock(WebPImage.class); mMockAnimatedDrawableBackendProvider = mock(AnimatedDrawableBackendProvider.class); mMockBitmapFactory = mock(PlatformBitmapFactory.class); mAnimatedImageFactory = new AnimatedImageFactoryImpl( mMockAnimatedDrawableBackendProvider,mMockBitmapFactory); ((AnimatedImageFactoryImpl) mAnimatedImageFactory).sWebpAnimatedimagedecoder = mWebPImageMock; }
@Test public void testCreateDefaults() { WebPImage mockWebPImage = mock(WebPImage.class); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mWebPImageMock.decode(byteBuffer.getNativePtr(),byteBuffer.size())) .thenReturn(mockWebPImage); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,FAKE_RESOURCE_RELEASER)); encodedImage.setimageFormat(ImageFormat.UNKNowN); CloseableAnimatedImage closeableImage = (CloseableAnimatedImage) mAnimatedImageFactory.decodeWebP( encodedImage,ImageDecodeOptions.defaults(),DEFAULT_BITMAP_CONfig); // Verify we got the right result AnimatedImageResult imageResult = closeableImage.getimageResult(); assertSame(mockWebPImage,imageResult.getimage()); assertNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verifyZeroInteractions(mMockAnimatedDrawableBackendProvider); verifyZeroInteractions(mMockBitmapFactory); }
@Before public void setup() { powermockito.mockStatic(WebPImage.class); mWebPImageMock = mock(WebPImage.class); mMockAnimatedDrawableBackendProvider = mock(AnimatedDrawableBackendProvider.class); mMockBitmapFactory = mock(PlatformBitmapFactory.class); mAnimatedImageFactory = new AnimatedImageFactoryImpl( mMockAnimatedDrawableBackendProvider,mMockBitmapFactory); ((AnimatedImageFactoryImpl) mAnimatedImageFactory).sWebpAnimatedimagedecoder = mWebPImageMock; }
@Test public void testCreateDefaults() { WebPImage mockWebPImage = mock(WebPImage.class); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mWebPImageMock.decode(byteBuffer.getNativePtr(),imageResult.getimage()); assertNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verifyZeroInteractions(mMockAnimatedDrawableBackendProvider); verifyZeroInteractions(mMockBitmapFactory); }
@Test public void testCreateWithPreviewBitmap() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap = MockBitmapFactory.create(50,50,DEFAULT_BITMAP_CONfig); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mWebPImageMock.decode(byteBuffer.getNativePtr(),byteBuffer.size())) .thenReturn(mockWebPImage); when(mockWebPImage.getWidth()).thenReturn(50); when(mockWebPImage.getHeight()).thenReturn(50); // For decoding preview frame,expect some calls. final AnimatedDrawableBackend mockAnimatedDrawableBackend = createAnimatedDrawableBackendMock(1); when(mMockAnimatedDrawableBackendProvider.get( any(AnimatedImageResult.class),isNull(Rect.class))) .thenReturn(mockAnimatedDrawableBackend); when(mMockBitmapFactory.createBitmapInternal(50,DEFAULT_BITMAP_CONfig)) .thenReturn(CloseableReference.of(mockBitmap,FAKE_BITMAP_RESOURCE_RELEASER)); AnimatedImageCompositor mockCompositor = mock(AnimatedImageCompositor.class); powermockito.whenNew(AnimatedImageCompositor.class) .withAnyArguments() .thenReturn(mockCompositor); ImageDecodeOptions imageDecodeOptions = ImageDecodeOptions.newBuilder() .setDecodePreviewFrame(true) .build(); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,FAKE_RESOURCE_RELEASER)); encodedImage.setimageFormat(ImageFormat.UNKNowN); CloseableAnimatedImage closeableImage = (CloseableAnimatedImage) mAnimatedImageFactory.decodeWebP( encodedImage,imageDecodeOptions,imageResult.getimage()); assertNotNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verify(mMockAnimatedDrawableBackendProvider).get( any(AnimatedImageResult.class),isNull(Rect.class)); verifyNoMoreInteractions(mMockAnimatedDrawableBackendProvider); verify(mMockBitmapFactory).createBitmapInternal(50,DEFAULT_BITMAP_CONfig); verifyNoMoreInteractions(mMockBitmapFactory); verify(mockCompositor).renderFrame(0,mockBitmap); }
@Test public void testCreateWithDecodeAlFrames() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap1 = MockBitmapFactory.create(50,DEFAULT_BITMAP_CONfig); Bitmap mockBitmap2 = MockBitmapFactory.create(50,expect some calls. final AnimatedDrawableBackend mockAnimatedDrawableBackend = createAnimatedDrawableBackendMock(2); when( mMockAnimatedDrawableBackendProvider.get( any(AnimatedImageResult.class),isNull(Rect.class))) .thenReturn(mockAnimatedDrawableBackend); when(mMockBitmapFactory.createBitmapInternal(50,DEFAULT_BITMAP_CONfig)) .thenReturn(CloseableReference.of(mockBitmap1,FAKE_BITMAP_RESOURCE_RELEASER)) .thenReturn(CloseableReference.of(mockBitmap2,FAKE_BITMAP_RESOURCE_RELEASER)); AnimatedImageCompositor mockCompositor = mock(AnimatedImageCompositor.class); powermockito.whenNew(AnimatedImageCompositor.class) .withAnyArguments() .thenReturn(mockCompositor); ImageDecodeOptions imageDecodeOptions = ImageDecodeOptions.newBuilder() .setDecodePreviewFrame(true) .setDecodeAllFrames(true) .build(); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,imageResult.getimage()); assertNotNull(imageResult.getDecodedFrame(0)); assertNotNull(imageResult.getDecodedFrame(1)); assertNotNull(imageResult.getPreviewBitmap()); // Should not have interacted with these. verify(mMockAnimatedDrawableBackendProvider).get( any(AnimatedImageResult.class),isNull(Rect.class)); verifyNoMoreInteractions(mMockAnimatedDrawableBackendProvider); verify(mMockBitmapFactory,times(2)).createBitmapInternal(50,mockBitmap1); verify(mockCompositor).renderFrame(1,mockBitmap2); }
@Test public void testCreateWithPreviewBitmap() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap = MockBitmapFactory.create(50,mockBitmap); }
@Test public void testCreateWithDecodeAlFrames() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap1 = MockBitmapFactory.create(50,mockBitmap2); }
com.facebook.imagepipeline.animated.base.AnimatedDrawable的实例源码
private Drawable createDrawableFromFetchedResult(Context context,CloseableImage image) { if (image instanceof CloseableStaticBitmap) { CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) image; BitmapDrawable bitmapDrawable = createBitmapDrawable(context,closeableStaticBitmap.getUnderlyingBitmap()); return (closeableStaticBitmap.getRotationAngle() != 0 && closeableStaticBitmap.getRotationAngle() != -1 ? new OrientedDrawable(bitmapDrawable,closeableStaticBitmap.getRotationAngle()) : bitmapDrawable); } else if (image instanceof CloseableAnimatedImage) { AnimatedDrawableFactory animatedDrawableFactory = Fresco.getimagePipelineFactory().getAnimatedFactory().getAnimatedDrawableFactory(context); if (animatedDrawableFactory != null) { AnimatedDrawable animatedDrawable = (AnimatedDrawable) animatedDrawableFactory.create(image); if (animatedDrawable != null) { return animatedDrawable; } } } throw new UnsupportedOperationException("Unrecognized image class: " + image); }
private Drawable createDrawableFromFetchedResult(Context context,closeableStaticBitmap.getRotationAngle()) : bitmapDrawable); } else if (image instanceof CloseableAnimatedImage) { AnimatedDrawableFactory animatedDrawableFactory = Fresco.getimagePipelineFactory().getAnimatedFactory().getAnimatedDrawableFactory(context); if (animatedDrawableFactory != null) { AnimatedDrawable animatedDrawable = (AnimatedDrawable) animatedDrawableFactory.create(image); if (animatedDrawable != null) { return animatedDrawable; } } } throw new UnsupportedOperationException("Unrecognized image class: " + image); }
private void handleAnimateBitmap(CloseableAnimatedImage animatedImage,int position) { AnimatedDrawableFactory animatedDrawableFactory = Fresco.getimagePipelineFactory().getAnimatedDrawableFactory(); AnimatedDrawable drawable = animatedDrawableFactory.create(animatedImage.getimageResult()); Bitmap bitmap = drawable2Bitmap(drawable); map.put(position,bitmap); }
com.facebook.imagepipeline.animated.base.AnimatedImageFrame的实例源码
private void renderImageSupportsScaling(Canvas canvas,AnimatedImageFrame frame) { double xScale = (double) mRenderedBounds.width() / (double) mAnimatedImage.getWidth(); double yScale = (double) mRenderedBounds.height() / (double) mAnimatedImage.getHeight(); int frameWidth = (int) Math.round(frame.getWidth() * xScale); int frameHeight = (int) Math.round(frame.getHeight() * yScale); int xOffset = (int) (frame.getXOffset() * xScale); int yOffset = (int) (frame.getYOffset() * yScale); synchronized (this) { prepareTempBitmapForThisSize(mRenderedBounds.width(),mRenderedBounds.height()); frame.renderFrame(frameWidth,frameHeight,mTempBitmap); // Temporary bitmap can be bigger than frame,so we should draw only rendered area of bitmap mRenderSrcRect.set(0,mRenderedBounds.width(),mRenderedBounds.height()); mRenderDstRect.set(xOffset,yOffset,mRenderedBounds.height()); canvas.drawBitmap(mTempBitmap,mRenderSrcRect,mRenderDstRect,null); } }
private void renderImageDoesNotSupportScaling(Canvas canvas,AnimatedImageFrame frame) { int frameWidth = frame.getWidth(); int frameHeight = frame.getHeight(); int xOffset = frame.getXOffset(); int yOffset = frame.getYOffset(); synchronized (this) { prepareTempBitmapForThisSize(frameWidth,frameHeight); frame.renderFrame(frameWidth,frameWidth,frameHeight); mRenderDstRect.set(0,frameHeight); float xScale = (float) mRenderedBounds.width() / (float) mAnimatedImage.getWidth(); float yScale = (float) mRenderedBounds.height() / (float) mAnimatedImage.getHeight(); canvas.save(); canvas.scale(xScale,yScale); canvas.translate(xOffset,yOffset); canvas.drawBitmap(mTempBitmap,null); canvas.restore(); } }
private void renderImageSupportsScaling(Canvas canvas,AnimatedImageFrame frame) { double xScale = (double) mRenderedBounds.width() / (double) mAnimatedImage.getWidth(); double yScale = (double) mRenderedBounds.height() / (double) mAnimatedImage.getHeight(); int frameWidth = (int) Math.round(frame.getWidth() * xScale); int frameHeight = (int) Math.round(frame.getHeight() * yScale); int xOffset = (int) (frame.getXOffset() * xScale); int yOffset = (int) (frame.getYOffset() * yScale); synchronized (this) { int renderedWidth = mRenderedBounds.width(); int renderedHeight = mRenderedBounds.height(); // Update the temp bitmap to be >= rendered dimensions prepareTempBitmapForThisSize(renderedWidth,renderedHeight); frame.renderFrame(frameWidth,mTempBitmap); // Temporary bitmap can be bigger than frame,renderedWidth,renderedHeight); mRenderDstRect.set(xOffset,xOffset + renderedWidth,yOffset + renderedHeight); canvas.drawBitmap(mTempBitmap,null); } }
private void renderImageDoesNotSupportScaling(Canvas canvas,null); canvas.restore(); } }
@Override public void renderFrame(int frameNumber,Canvas canvas) { AnimatedImageFrame frame = mAnimatedImage.getFrame(frameNumber); try { if (mAnimatedImage.doesRenderSupportScaling()) { renderImageSupportsScaling(canvas,frame); } else { renderImageDoesNotSupportScaling(canvas,frame); } } finally { frame.dispose(); } }
@Override public void renderFrame(int frameNumber,frame); } } finally { frame.dispose(); } }
com.facebook.imagepipeline.animated.base.AnimatedImageResult的实例源码
public AnimatedDrawableBackendImpl( AnimatedDrawableutil animatedDrawableutil,AnimatedImageResult animatedImageResult,Rect bounds) { mAnimatedDrawableutil = animatedDrawableutil; mAnimatedImageResult = animatedImageResult; mAnimatedImage = animatedImageResult.getimage(); mFrameDurationsMs = mAnimatedImage.getFrameDurations(); mAnimatedDrawableutil.fixFrameDurations(mFrameDurationsMs); mDurationMs = mAnimatedDrawableutil.getTotalDurationFromFrameDurations(mFrameDurationsMs); mFrameTimestampsMs = mAnimatedDrawableutil.getFrameTimeStampsFromDurations(mFrameDurationsMs); mRenderedBounds = getBoundsToUse(mAnimatedImage,bounds); mFrameInfos = new AnimatedDrawableFrameInfo[mAnimatedImage.getFrameCount()]; for (int i = 0; i < mAnimatedImage.getFrameCount(); i++) { mFrameInfos[i] = mAnimatedImage.getFrameInfo(i); } }
public AnimatedDrawableBackendImpl( AnimatedDrawableutil animatedDrawableutil,bounds); mFrameInfos = new AnimatedDrawableFrameInfo[mAnimatedImage.getFrameCount()]; for (int i = 0; i < mAnimatedImage.getFrameCount(); i++) { mFrameInfos[i] = mAnimatedImage.getFrameInfo(i); } }
private AnimationBackend createAnimationBackend(AnimatedImageResult animatedImageResult) { AnimatedDrawableBackend animatedDrawableBackend = createAnimatedDrawableBackend(animatedImageResult); BitmapFrameCache bitmapFrameCache = createBitmapFrameCache(animatedImageResult); BitmapFrameRenderer bitmapFrameRenderer = new AnimatedDrawableBackendFrameRenderer(bitmapFrameCache,animatedDrawableBackend); int numberOfFramesToPrefetch = mNumberOfFramesToPreparesupplier.get(); BitmapFramePreparationStrategy bitmapFramePreparationStrategy = null; BitmapFramePreparer bitmapFramePreparer = null; if (numberOfFramesToPrefetch > 0) { bitmapFramePreparationStrategy = new FixednumberBitmapFramePreparationStrategy(); bitmapFramePreparer = createBitmapFramePreparer(bitmapFrameRenderer); } BitmapAnimationBackend bitmapAnimationBackend = new BitmapAnimationBackend( mPlatformBitmapFactory,bitmapFrameCache,new AnimatedDrawableBackendAnimationinformation(animatedDrawableBackend),bitmapFrameRenderer,bitmapFramePreparationStrategy,bitmapFramePreparer); return AnimationBackendDelegateWithInactivityCheck.createForBackend( bitmapAnimationBackend,mMonotonicclock,mscheduledexecutorserviceForUiThread); }
private BitmapFrameCache createBitmapFrameCache(AnimatedImageResult animatedImageResult) { switch (mCachingStrategysupplier.get()) { case CACHING_STRATEGY_FRESCO_CACHE: return new FrescoFrameCache(createAnimatedFrameCache(animatedImageResult),true); case CACHING_STRATEGY_FRESCO_CACHE_NO_REUSING: return new FrescoFrameCache(createAnimatedFrameCache(animatedImageResult),false); case CACHING_STRATEGY_KEEP_LAST_CACHE: return new KeepLastFrameCache(); case CACHING_STRATEGY_NO_CACHE: default: return new NoOpCache(); } }
private AnimatedDrawableBackendProvider getAnimatedDrawableBackendProvider() { if (mAnimatedDrawableBackendProvider == null) { mAnimatedDrawableBackendProvider = new AnimatedDrawableBackendProvider() { @Override public AnimatedDrawableBackend get(AnimatedImageResult animatedImageResult,Rect bounds) { return new AnimatedDrawableBackendImpl( getAnimatedDrawableutil(),animatedImageResult,bounds); } }; } return mAnimatedDrawableBackendProvider; }
private AnimatedImageFactory buildAnimatedImageFactory() { AnimatedDrawableBackendProvider animatedDrawableBackendProvider = new AnimatedDrawableBackendProvider() { @Override public AnimatedDrawableBackend get(AnimatedImageResult imageResult,Rect bounds) { return new AnimatedDrawableBackendImpl(getAnimatedDrawableutil(),imageResult,bounds); } }; return new AnimatedImageFactoryImpl(animatedDrawableBackendProvider,mPlatformBitmapFactory); }
@Override public void close() { AnimatedImageResult imageResult; synchronized (this) { if (mImageResult == null) { return; } imageResult = mImageResult; mImageResult = null; } imageResult.dispose(); }
private CloseableImage getCloseableImage( ImageDecodeOptions options,AnimatedImage image,Bitmap.Config bitmapConfig) { List<CloseableReference<Bitmap>> decodedFrames = null; CloseableReference<Bitmap> previewBitmap = null; try { final int frameForPreview = options.useLastFrameForPreview ? image.getFrameCount() - 1 : 0; if (options.forceStaticImage) { return new CloseableStaticBitmap( createPreviewBitmap(image,bitmapConfig,frameForPreview),ImmutableQualityInfo.FULL_QUALITY,0); } if (options.decodeAllFrames) { decodedFrames = decodeAllFrames(image,bitmapConfig); previewBitmap = CloseableReference.cloneOrNull(decodedFrames.get(frameForPreview)); } if (options.decodePreviewFrame && previewBitmap == null) { previewBitmap = createPreviewBitmap(image,frameForPreview); } AnimatedImageResult animatedImageResult = AnimatedImageResult.newBuilder(image) .setPreviewBitmap(previewBitmap) .setFrameForPreview(frameForPreview) .setDecodedFrames(decodedFrames) .build(); return new CloseableAnimatedImage(animatedImageResult); } finally { CloseableReference.closeSafely(previewBitmap); CloseableReference.closeSafely(decodedFrames); } }
@Test public void testCreateDefaults() { WebPImage mockWebPImage = mock(WebPImage.class); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mWebPImageMock.decode(byteBuffer.getNativePtr(),byteBuffer.size())) .thenReturn(mockWebPImage); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,FAKE_RESOURCE_RELEASER)); encodedImage.setimageFormat(ImageFormat.UNKNowN); CloseableAnimatedImage closeableImage = (CloseableAnimatedImage) mAnimatedImageFactory.decodeWebP( encodedImage,ImageDecodeOptions.defaults(),DEFAULT_BITMAP_CONfig); // Verify we got the right result AnimatedImageResult imageResult = closeableImage.getimageResult(); assertSame(mockWebPImage,imageResult.getimage()); assertNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verifyZeroInteractions(mMockAnimatedDrawableBackendProvider); verifyZeroInteractions(mMockBitmapFactory); }
@Test public void testCreateDefaults() { GifImage mockGifImage = mock(GifImage.class); // Expect a call to GifImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mGifImageMock.decode(byteBuffer.getNativePtr(),byteBuffer.size())) .thenReturn(mockGifImage); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,FAKE_RESOURCE_RELEASER)); encodedImage.setimageFormat(ImageFormat.UNKNowN); CloseableAnimatedImage closeableImage = (CloseableAnimatedImage) mAnimatedImageFactory.decodeGif( encodedImage,DEFAULT_BITMAP_CONfig); // Verify we got the right result AnimatedImageResult imageResult = closeableImage.getimageResult(); assertSame(mockGifImage,imageResult.getimage()); assertNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verifyZeroInteractions(mMockAnimatedDrawableBackendProvider); verifyZeroInteractions(mMockBitmapFactory); }
private AnimationBackend createAnimationBackend(AnimatedImageResult animatedImageResult) { AnimatedDrawableBackend animatedDrawableBackend = createAnimatedDrawableBackend(animatedImageResult); BitmapFrameCache bitmapFrameCache = createBitmapFrameCache(animatedImageResult); BitmapFrameRenderer bitmapFrameRenderer = new AnimatedDrawableBackendFrameRenderer(bitmapFrameCache,animatedDrawableBackend); int numberOfFramesToPrefetch = mNumberOfFramesToPreparesupplier.get(); BitmapFramePreparationStrategy bitmapFramePreparationStrategy = null; BitmapFramePreparer bitmapFramePreparer = null; if (numberOfFramesToPrefetch > 0) { bitmapFramePreparationStrategy = new FixednumberBitmapFramePreparationStrategy(numberOfFramesToPrefetch); bitmapFramePreparer = createBitmapFramePreparer(bitmapFrameRenderer); } BitmapAnimationBackend bitmapAnimationBackend = new BitmapAnimationBackend( mPlatformBitmapFactory,mscheduledexecutorserviceForUiThread); }
private BitmapFrameCache createBitmapFrameCache(AnimatedImageResult animatedImageResult) { switch (mCachingStrategysupplier.get()) { case CACHING_STRATEGY_FRESCO_CACHE: return new FrescoFrameCache(createAnimatedFrameCache(animatedImageResult),false); case CACHING_STRATEGY_KEEP_LAST_CACHE: return new KeepLastFrameCache(); case CACHING_STRATEGY_NO_CACHE: default: return new NoOpCache(); } }
private AnimatedDrawableBackendProvider getAnimatedDrawableBackendProvider() { if (mAnimatedDrawableBackendProvider == null) { mAnimatedDrawableBackendProvider = new AnimatedDrawableBackendProvider() { @Override public AnimatedDrawableBackend get(AnimatedImageResult animatedImageResult,bounds); } }; } return mAnimatedDrawableBackendProvider; }
private AnimatedImageFactory buildAnimatedImageFactory() { AnimatedDrawableBackendProvider animatedDrawableBackendProvider = new AnimatedDrawableBackendProvider() { @Override public AnimatedDrawableBackend get(AnimatedImageResult imageResult,mPlatformBitmapFactory); }
@Override public void close() { AnimatedImageResult imageResult; synchronized (this) { if (mImageResult == null) { return; } imageResult = mImageResult; mImageResult = null; } imageResult.dispose(); }
private CloseableImage getCloseableImage( ImageDecodeOptions options,frameForPreview); } AnimatedImageResult animatedImageResult = AnimatedImageResult.newBuilder(image) .setPreviewBitmap(previewBitmap) .setFrameForPreview(frameForPreview) .setDecodedFrames(decodedFrames) .build(); return new CloseableAnimatedImage(animatedImageResult); } finally { CloseableReference.closeSafely(previewBitmap); CloseableReference.closeSafely(decodedFrames); } }
@Test public void testCreateDefaults() { WebPImage mockWebPImage = mock(WebPImage.class); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mWebPImageMock.decode(byteBuffer.getNativePtr(),imageResult.getimage()); assertNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verifyZeroInteractions(mMockAnimatedDrawableBackendProvider); verifyZeroInteractions(mMockBitmapFactory); }
@Test public void testCreateDefaults() { GifImage mockGifImage = mock(GifImage.class); // Expect a call to GifImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mGifImageMock.decode(byteBuffer.getNativePtr(),imageResult.getimage()); assertNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verifyZeroInteractions(mMockAnimatedDrawableBackendProvider); verifyZeroInteractions(mMockBitmapFactory); }
private AnimatedDrawableBackend createAnimatedDrawableBackend( AnimatedImageResult animatedImageResult) { AnimatedImage animatedImage = animatedImageResult.getimage(); Rect initialBounds = new Rect(0,animatedImage.getWidth(),animatedImage.getHeight()); return mAnimatedDrawableBackendProvider.get(animatedImageResult,initialBounds); }
private AnimatedFrameCache createAnimatedFrameCache( final AnimatedImageResult animatedImageResult) { return new AnimatedFrameCache( new AnimationFrameCacheKey(animatedImageResult.hashCode()),mbackingCache); }
public CloseableAnimatedImage(AnimatedImageResult imageResult) { mImageResult = imageResult; }
public synchronized AnimatedImageResult getimageResult() { return mImageResult; }
@Override public AnimatedImageResult getAnimatedImageResult() { return mAnimatedImageResult; }
@Override public AnimatedImageResult getAnimatedImageResult() { return null; }
@Test public void testCreateWithPreviewBitmap() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap = MockBitmapFactory.create(50,50,DEFAULT_BITMAP_CONfig); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mWebPImageMock.decode(byteBuffer.getNativePtr(),byteBuffer.size())) .thenReturn(mockWebPImage); when(mockWebPImage.getWidth()).thenReturn(50); when(mockWebPImage.getHeight()).thenReturn(50); // For decoding preview frame,expect some calls. final AnimatedDrawableBackend mockAnimatedDrawableBackend = createAnimatedDrawableBackendMock(1); when(mMockAnimatedDrawableBackendProvider.get( any(AnimatedImageResult.class),isNull(Rect.class))) .thenReturn(mockAnimatedDrawableBackend); when(mMockBitmapFactory.createBitmapInternal(50,DEFAULT_BITMAP_CONfig)) .thenReturn(CloseableReference.of(mockBitmap,FAKE_BITMAP_RESOURCE_RELEASER)); AnimatedImageCompositor mockCompositor = mock(AnimatedImageCompositor.class); powermockito.whenNew(AnimatedImageCompositor.class) .withAnyArguments() .thenReturn(mockCompositor); ImageDecodeOptions imageDecodeOptions = ImageDecodeOptions.newBuilder() .setDecodePreviewFrame(true) .build(); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,FAKE_RESOURCE_RELEASER)); encodedImage.setimageFormat(ImageFormat.UNKNowN); CloseableAnimatedImage closeableImage = (CloseableAnimatedImage) mAnimatedImageFactory.decodeWebP( encodedImage,imageDecodeOptions,imageResult.getimage()); assertNotNull(imageResult.getPreviewBitmap()); assertFalse(imageResult.hasDecodedFrame(0)); // Should not have interacted with these. verify(mMockAnimatedDrawableBackendProvider).get( any(AnimatedImageResult.class),isNull(Rect.class)); verifyNoMoreInteractions(mMockAnimatedDrawableBackendProvider); verify(mMockBitmapFactory).createBitmapInternal(50,DEFAULT_BITMAP_CONfig); verifyNoMoreInteractions(mMockBitmapFactory); verify(mockCompositor).renderFrame(0,mockBitmap); }
@Test public void testCreateWithDecodeAlFrames() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap1 = MockBitmapFactory.create(50,DEFAULT_BITMAP_CONfig); Bitmap mockBitmap2 = MockBitmapFactory.create(50,expect some calls. final AnimatedDrawableBackend mockAnimatedDrawableBackend = createAnimatedDrawableBackendMock(2); when( mMockAnimatedDrawableBackendProvider.get( any(AnimatedImageResult.class),isNull(Rect.class))) .thenReturn(mockAnimatedDrawableBackend); when(mMockBitmapFactory.createBitmapInternal(50,DEFAULT_BITMAP_CONfig)) .thenReturn(CloseableReference.of(mockBitmap1,FAKE_BITMAP_RESOURCE_RELEASER)) .thenReturn(CloseableReference.of(mockBitmap2,FAKE_BITMAP_RESOURCE_RELEASER)); AnimatedImageCompositor mockCompositor = mock(AnimatedImageCompositor.class); powermockito.whenNew(AnimatedImageCompositor.class) .withAnyArguments() .thenReturn(mockCompositor); ImageDecodeOptions imageDecodeOptions = ImageDecodeOptions.newBuilder() .setDecodePreviewFrame(true) .setDecodeAllFrames(true) .build(); EncodedImage encodedImage = new EncodedImage( CloseableReference.of(byteBuffer,imageResult.getimage()); assertNotNull(imageResult.getDecodedFrame(0)); assertNotNull(imageResult.getDecodedFrame(1)); assertNotNull(imageResult.getPreviewBitmap()); // Should not have interacted with these. verify(mMockAnimatedDrawableBackendProvider).get( any(AnimatedImageResult.class),isNull(Rect.class)); verifyNoMoreInteractions(mMockAnimatedDrawableBackendProvider); verify(mMockBitmapFactory,times(2)).createBitmapInternal(50,mockBitmap1); verify(mockCompositor).renderFrame(1,mockBitmap2); }
@Test public void testCreateWithPreviewBitmap() throws Exception { GifImage mockGifImage = mock(GifImage.class); Bitmap mockBitmap = MockBitmapFactory.create(50,DEFAULT_BITMAP_CONfig); // Expect a call to WebPImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mGifImageMock.decode(byteBuffer.getNativePtr(),byteBuffer.size())) .thenReturn(mockGifImage); when(mockGifImage.getWidth()).thenReturn(50); when(mockGifImage.getHeight()).thenReturn(50); // For decoding preview frame,expect some calls. final AnimatedDrawableBackend mockAnimatedDrawableBackend = createAnimatedDrawableBackendMock(1); when(mMockAnimatedDrawableBackendProvider.get( any(AnimatedImageResult.class),FAKE_RESOURCE_RELEASER)); encodedImage.setimageFormat(ImageFormat.UNKNowN); CloseableAnimatedImage closeableImage = (CloseableAnimatedImage) mAnimatedImageFactory.decodeGif( encodedImage,mockBitmap); }
@Test public void testCreateWithDecodeAlFrames() throws Exception { GifImage mockGifImage = mock(GifImage.class); Bitmap mockBitmap1 = MockBitmapFactory.create(50,DEFAULT_BITMAP_CONfig); // Expect a call to GifImage.create TrivialPooledByteBuffer byteBuffer = createByteBuffer(); when(mGifImageMock.decode(byteBuffer.getNativePtr(),expect some calls. final AnimatedDrawableBackend mockAnimatedDrawableBackend = createAnimatedDrawableBackendMock(2); when( mMockAnimatedDrawableBackendProvider.get( any(AnimatedImageResult.class),mockBitmap2); }
private AnimatedDrawableBackend createAnimatedDrawableBackend( AnimatedImageResult animatedImageResult) { AnimatedImage animatedImage = animatedImageResult.getimage(); Rect initialBounds = new Rect(0,initialBounds); }
private AnimatedFrameCache createAnimatedFrameCache( final AnimatedImageResult animatedImageResult) { return new AnimatedFrameCache( new AnimationFrameCacheKey(animatedImageResult.hashCode()),mbackingCache); }
public CloseableAnimatedImage(AnimatedImageResult imageResult) { mImageResult = imageResult; }
public synchronized AnimatedImageResult getimageResult() { return mImageResult; }
@Override public AnimatedImageResult getAnimatedImageResult() { return mAnimatedImageResult; }
@Override public AnimatedImageResult getAnimatedImageResult() { return null; }
@Test public void testCreateWithPreviewBitmap() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap = MockBitmapFactory.create(50,mockBitmap); }
@Test public void testCreateWithDecodeAlFrames() throws Exception { WebPImage mockWebPImage = mock(WebPImage.class); Bitmap mockBitmap1 = MockBitmapFactory.create(50,mockBitmap2); }
@Test public void testCreateWithPreviewBitmap() throws Exception { GifImage mockGifImage = mock(GifImage.class); Bitmap mockBitmap = MockBitmapFactory.create(50,mockBitmap); }
@Test public void testCreateWithDecodeAlFrames() throws Exception { GifImage mockGifImage = mock(GifImage.class); Bitmap mockBitmap1 = MockBitmapFactory.create(50,mockBitmap2); }
/** * Creates a new {@link AnimatedDrawableBackend}. * * @param animatedImageResult the image result. * @param bounds the initial bounds for the drawable * @return a new {@link AnimatedDrawableBackend} */ AnimatedDrawableBackend get(AnimatedImageResult animatedImageResult,Rect bounds);
/** * Creates a new {@link AnimatedDrawableBackend}. * * @param animatedImageResult the image result. * @param bounds the initial bounds for the drawable * @return a new {@link AnimatedDrawableBackend} */ AnimatedDrawableBackend get(AnimatedImageResult animatedImageResult,Rect bounds);
关于com.facebook.imagepipeline.image.EncodedImage的实例源码和facebook源代码的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于com.facebook.animated.webp.WebPImage的实例源码、com.facebook.imagepipeline.animated.base.AnimatedDrawable的实例源码、com.facebook.imagepipeline.animated.base.AnimatedImageFrame的实例源码、com.facebook.imagepipeline.animated.base.AnimatedImageResult的实例源码的相关知识,请在本站寻找。
本文标签: