Java Code Examples for com.facebook.common.references.CloseableReference#of()
The following examples show how to use
com.facebook.common.references.CloseableReference#of() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmptyJpegGenerator.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
public CloseableReference<PooledByteBuffer> generate(short width, short height) { PooledByteBufferOutputStream os = null; try { os = mPooledByteBufferFactory.newOutputStream( EMPTY_JPEG_PREFIX.length + EMPTY_JPEG_SUFFIX.length + 4); os.write(EMPTY_JPEG_PREFIX); os.write((byte) (height >> 8)); os.write((byte) (height & 0x00ff)); os.write((byte) (width >> 8)); os.write((byte) (width & 0x00ff)); os.write(EMPTY_JPEG_SUFFIX); return CloseableReference.of(os.toByteBuffer()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (os != null) { os.close(); } } }
Example 2
Source File: CountingMemoryCacheTest.java From fresco with MIT License | 6 votes |
@Before public void setUp() { MockitoAnnotations.initMocks(this); PowerMockito.mockStatic(SystemClock.class); PowerMockito.when(SystemClock.uptimeMillis()).thenReturn(0L); mValueDescriptor = new ValueDescriptor<Integer>() { @Override public int getSizeInBytes(Integer value) { return value; } }; mParams = new MemoryCacheParams( CACHE_MAX_SIZE, CACHE_MAX_COUNT, CACHE_EVICTION_QUEUE_MAX_SIZE, CACHE_EVICTION_QUEUE_MAX_COUNT, CACHE_ENTRY_MAX_SIZE, PARAMS_CHECK_INTERVAL_MS); when(mParamsSupplier.get()).thenReturn(mParams); mBitmapReference = CloseableReference.of(mBitmap, FAKE_BITMAP_RESOURCE_RELEASER); mCache = new CountingMemoryCache<>(mValueDescriptor, mCacheTrimStrategy, mParamsSupplier, null); }
Example 3
Source File: AnimatedImageFactoryWebPImplTest.java From fresco with MIT License | 6 votes |
private void testCreateDefaults(WebPImage mockWebPImage, PooledByteBuffer byteBuffer) { 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); }
Example 4
Source File: CloseableImageCopier.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
private CloseableReference<CloseableImage> copyCloseableStaticBitmap( final CloseableReference<CloseableImage> closeableStaticBitmapRef) { Bitmap sourceBitmap = ((CloseableStaticBitmap) closeableStaticBitmapRef.get()) .getUnderlyingBitmap(); CloseableReference<Bitmap> bitmapRef = mPlatformBitmapFactory.createBitmap( sourceBitmap.getWidth(), sourceBitmap.getHeight()); try { Bitmap destinationBitmap = bitmapRef.get(); Preconditions.checkState(!destinationBitmap.isRecycled()); Preconditions.checkState(destinationBitmap.isMutable()); Bitmaps.copyBitmap(destinationBitmap, sourceBitmap); return CloseableReference.<CloseableImage>of( new CloseableStaticBitmap(bitmapRef, ImmutableQualityInfo.FULL_QUALITY)); } finally { bitmapRef.close(); } }
Example 5
Source File: AnimatedSingleUsePostprocessorProducerTest.java From fresco with MIT License | 6 votes |
@Test public void testNonStaticBitmapIsPassedOn() { SingleUsePostprocessorConsumer postprocessorConsumer = produceResults(); CloseableAnimatedImage sourceCloseableAnimatedImage = mock(CloseableAnimatedImage.class); CloseableReference<CloseableImage> sourceCloseableImageRef = CloseableReference.<CloseableImage>of(sourceCloseableAnimatedImage); postprocessorConsumer.onNewResult(sourceCloseableImageRef, Consumer.IS_LAST); sourceCloseableImageRef.close(); mTestExecutorService.runUntilIdle(); mInOrder.verify(mConsumer).onNewResult(any(CloseableReference.class), eq(Consumer.IS_LAST)); mInOrder.verifyNoMoreInteractions(); assertEquals(1, mResults.size()); CloseableReference<CloseableImage> res0 = mResults.get(0); assertTrue(CloseableReference.isValid(res0)); assertSame(sourceCloseableAnimatedImage, res0.get()); res0.close(); verify(sourceCloseableAnimatedImage).close(); }
Example 6
Source File: EncodedImageTest.java From fresco with MIT License | 5 votes |
@Test public void testIsJpegCompleteAt_Complete() { byte[] encodedBytes = new byte[ENCODED_BYTES_LENGTH]; encodedBytes[ENCODED_BYTES_LENGTH - 2] = (byte) JfifUtil.MARKER_FIRST_BYTE; encodedBytes[ENCODED_BYTES_LENGTH - 1] = (byte) JfifUtil.MARKER_EOI; PooledByteBuffer buf = new TrivialPooledByteBuffer(encodedBytes); EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf)); encodedImage.setImageFormat(DefaultImageFormats.JPEG); assertTrue(encodedImage.isCompleteAt(ENCODED_BYTES_LENGTH)); }
Example 7
Source File: MemoryPooledByteBufferOutputStream.java From fresco with MIT License | 5 votes |
/** * Reallocate the local buffer to hold the new length specified. Also copy over existing data to * this new buffer * * @param newLength new length of buffer * @throws InvalidStreamException if the stream is invalid * @throws BasePool.SizeTooLargeException if the allocation from the pool fails */ @VisibleForTesting void realloc(int newLength) { ensureValid(); /* Can the buffer handle @i more bytes, if not expand it */ if (newLength <= mBufRef.get().getSize()) { return; } MemoryChunk newbuf = mPool.get(newLength); mBufRef.get().copy(0, newbuf, 0, mCount); mBufRef.close(); mBufRef = CloseableReference.of(newbuf, mPool); }
Example 8
Source File: SingleUsePostprocessorProducerTest.java From fresco with MIT License | 5 votes |
@Before public void setUp() { MockitoAnnotations.initMocks(this); mTestExecutorService = new TestExecutorService(new FakeClock()); mPostprocessorProducer = new PostprocessorProducer(mInputProducer, mPlatformBitmapFactory, mTestExecutorService); when(mImageRequest.getPostprocessor()).thenReturn(mPostprocessor); when(mProducerContext.getId()).thenReturn(mRequestId); when(mProducerContext.getProducerListener()).thenReturn(mProducerListener); when(mProducerContext.getImageRequest()).thenReturn(mImageRequest); mResults = new ArrayList<>(); when(mPostprocessor.getName()).thenReturn(POSTPROCESSOR_NAME); when(mProducerListener.requiresExtraMap(mProducerContext, PRODUCER_NAME)).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); mSourceBitmap = mock(Bitmap.class); mSourceCloseableStaticBitmap = mock(CloseableStaticBitmap.class); when(mSourceCloseableStaticBitmap.getUnderlyingBitmap()).thenReturn(mSourceBitmap); mSourceCloseableImageRef = CloseableReference.<CloseableImage>of(mSourceCloseableStaticBitmap); mDestinationBitmap = mock(Bitmap.class); mDestinationCloseableBitmapRef = CloseableReference.of(mDestinationBitmap, mBitmapResourceReleaser); }
Example 9
Source File: MemoryPooledByteBufferFactory.java From fresco with MIT License | 5 votes |
@Override public MemoryPooledByteBuffer newByteBuffer(int size) { Preconditions.checkArgument(size > 0); CloseableReference<MemoryChunk> chunkRef = CloseableReference.of(mPool.get(size), mPool); try { return new MemoryPooledByteBuffer(chunkRef, size); } finally { chunkRef.close(); } }
Example 10
Source File: DecodeProducer.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Notifies consumer of new result and finishes if the result is final. */ private void handleResult(final CloseableImage decodedImage, final boolean isFinal) { CloseableReference<CloseableImage> decodedImageRef = CloseableReference.of(decodedImage); try { maybeFinish(isFinal); mConsumer.onNewResult(decodedImageRef, isFinal); } finally { CloseableReference.closeSafely(decodedImageRef); } }
Example 11
Source File: EncodedImageTest.java From fresco with MIT License | 5 votes |
@Test public void testParseMetaData_JPEG() throws IOException { PooledByteBuffer buf = new TrivialPooledByteBuffer( ByteStreams.toByteArray( EncodedImageTest.class.getResourceAsStream("images/image.jpg"))); EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf)); encodedImage.parseMetaData(); assertSame(DefaultImageFormats.JPEG, encodedImage.getImageFormat()); assertEquals(550, encodedImage.getWidth()); assertEquals(468, encodedImage.getHeight()); assertEquals(0, encodedImage.getRotationAngle()); assertEquals(0, encodedImage.getExifOrientation()); }
Example 12
Source File: ArtBitmapFactory.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
@SuppressLint("NewApi") private CloseableReference<Bitmap> doDecodeStaticImage(InputStream inputStream) { inputStream.mark(Integer.MAX_VALUE); final BitmapFactory.Options options = getDecodeOptionsForStream(inputStream); try { inputStream.reset(); } catch (IOException ioe) { throw new RuntimeException(ioe); } final Bitmap bitmapToReuse = mBitmapPool.get(options.outHeight * options.outWidth); if (bitmapToReuse == null) { throw new NullPointerException("BitmapPool.get returned null"); } options.inBitmap = bitmapToReuse; Bitmap decodedBitmap; try { decodedBitmap = BitmapFactory.decodeStream(inputStream, null, options); } catch (RuntimeException re) { mBitmapPool.release(bitmapToReuse); throw re; } if (bitmapToReuse != decodedBitmap) { mBitmapPool.release(bitmapToReuse); decodedBitmap.recycle(); throw new IllegalStateException(); } return CloseableReference.of(decodedBitmap, mBitmapPool); }
Example 13
Source File: DalvikPurgeableDecoder.java From fresco with MIT License | 5 votes |
/** * Pin the bitmap so that it cannot be 'purged'. Only makes sense for purgeable bitmaps WARNING: * Use with caution. Make sure that the pinned bitmap is recycled eventually. Otherwise, this will * simply eat up ashmem memory and eventually lead to unfortunate crashes. We *may* eventually * provide an unpin method - but we don't yet have a compelling use case for that. * * @param bitmap the purgeable bitmap to pin */ public CloseableReference<Bitmap> pinBitmap(Bitmap bitmap) { Preconditions.checkNotNull(bitmap); try { // Real decoding happens here - if the image was corrupted, this will throw an exception nativePinBitmap(bitmap); } catch (Exception e) { bitmap.recycle(); throw Throwables.propagate(e); } if (!mUnpooledBitmapsCounter.increase(bitmap)) { int bitmapSize = BitmapUtil.getSizeInBytes(bitmap); bitmap.recycle(); String detailMessage = String.format( Locale.US, "Attempted to pin a bitmap of size %d bytes." + " The current pool count is %d, the current pool size is %d bytes." + " The current pool max count is %d, the current pool max size is %d bytes.", bitmapSize, mUnpooledBitmapsCounter.getCount(), mUnpooledBitmapsCounter.getSize(), mUnpooledBitmapsCounter.getMaxCount(), mUnpooledBitmapsCounter.getMaxSize()); throw new TooManyBitmapsException(detailMessage); } return CloseableReference.of(bitmap, mUnpooledBitmapsCounter.getReleaser()); }
Example 14
Source File: EncodedImageTest.java From fresco with MIT License | 5 votes |
@Test public void testIsJpegCompleteAt_notComplete() { byte[] encodedBytes = new byte[ENCODED_BYTES_LENGTH]; encodedBytes[ENCODED_BYTES_LENGTH - 2] = 0; encodedBytes[ENCODED_BYTES_LENGTH - 1] = 0; PooledByteBuffer buf = new TrivialPooledByteBuffer(encodedBytes); EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf)); encodedImage.setImageFormat(DefaultImageFormats.JPEG); assertFalse(encodedImage.isCompleteAt(ENCODED_BYTES_LENGTH)); }
Example 15
Source File: BitmapAnimationBackendTest.java From fresco with MIT License | 5 votes |
@Before public void setup() { MockitoAnnotations.initMocks(this); mBitmapRefererence = CloseableReference.of(mBitmap, mBitmapResourceReleaser); mBitmapAnimationBackend = new BitmapAnimationBackend( mPlatformBitmapFactory, mBitmapFrameCache, mAnimationInformation, mBitmapFrameRenderer, mBitmapFramePreparationStrategy, mBitmapFramePreparer); mBitmapAnimationBackend.setFrameListener(mFrameListener); }
Example 16
Source File: FrescoUtil.java From ImageLoader with Apache License 2.0 | 5 votes |
public static void putIntoPool(Bitmap bitmap,String uriString) { final ImageRequest requestBmp = ImageRequest.fromUri(uriString); // 赋值 // 获得 Key CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getBitmapCacheKey(requestBmp, ImageLoader.context); // 获得 closeableReference CloseableReference<CloseableImage> closeableReference = CloseableReference.<CloseableImage>of( new CloseableStaticBitmap(bitmap, SimpleBitmapReleaser.getInstance(), ImmutableQualityInfo.FULL_QUALITY, 0)); // 存入 Fresco Fresco.getImagePipelineFactory().getBitmapMemoryCache().cache(cacheKey, closeableReference); }
Example 17
Source File: MemoryPooledByteBufferTest.java From fresco with MIT License | 5 votes |
@Before public void setUp() { mAshmemChunk = new FakeAshmemMemoryChunk(BYTES.length); mAshmemChunk.write(0, BYTES, 0, BYTES.length); mAshmemPool = mock(AshmemMemoryChunkPool.class); CloseableReference<MemoryChunk> bufferPoolRef = CloseableReference.of(mAshmemChunk, mAshmemPool); mBufferPooledByteBuffer = new MemoryPooledByteBuffer(bufferPoolRef, BUFFER_LENGTH); bufferPoolRef.close(); }
Example 18
Source File: AnimatedRepeatedPostprocessorProducerTest.java From fresco with MIT License | 4 votes |
private void setupNewSourceImage() { mSourceBitmap = mock(Bitmap.class); mSourceCloseableStaticBitmap = mock(CloseableStaticBitmap.class); when(mSourceCloseableStaticBitmap.getUnderlyingBitmap()).thenReturn(mSourceBitmap); mSourceCloseableImageRef = CloseableReference.<CloseableImage>of(mSourceCloseableStaticBitmap); }
Example 19
Source File: FlexByteArrayPool.java From fresco with MIT License | 4 votes |
public CloseableReference<byte[]> get(int size) { return CloseableReference.of(mDelegatePool.get(size), mResourceReleaser); }
Example 20
Source File: ResizeAndRotateProducer.java From fresco with MIT License | 4 votes |
private void doTransform( EncodedImage encodedImage, @Status int status, ImageTranscoder imageTranscoder) { mProducerContext.getProducerListener().onProducerStart(mProducerContext, PRODUCER_NAME); ImageRequest imageRequest = mProducerContext.getImageRequest(); PooledByteBufferOutputStream outputStream = mPooledByteBufferFactory.newOutputStream(); Map<String, String> extraMap = null; EncodedImage ret; try { ImageTranscodeResult result = imageTranscoder.transcode( encodedImage, outputStream, imageRequest.getRotationOptions(), imageRequest.getResizeOptions(), null, DEFAULT_JPEG_QUALITY); if (result.getTranscodeStatus() == TranscodeStatus.TRANSCODING_ERROR) { throw new RuntimeException("Error while transcoding the image"); } extraMap = getExtraMap( encodedImage, imageRequest.getResizeOptions(), result, imageTranscoder.getIdentifier()); CloseableReference<PooledByteBuffer> ref = CloseableReference.of(outputStream.toByteBuffer()); try { ret = new EncodedImage(ref); ret.setImageFormat(JPEG); try { ret.parseMetaData(); mProducerContext .getProducerListener() .onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, extraMap); if (result.getTranscodeStatus() != TranscodeStatus.TRANSCODING_NO_RESIZING) { status |= Consumer.IS_RESIZING_DONE; } getConsumer().onNewResult(ret, status); } finally { EncodedImage.closeSafely(ret); } } finally { CloseableReference.closeSafely(ref); } } catch (Exception e) { mProducerContext .getProducerListener() .onProducerFinishWithFailure(mProducerContext, PRODUCER_NAME, e, extraMap); if (isLast(status)) { getConsumer().onFailure(e); } return; } finally { outputStream.close(); } }