Search in sources :

Example 1 with CloseableImage

use of com.facebook.imagepipeline.image.CloseableImage in project DevRing by LJYcoder.

the class FrescoManager method getBitmap.

@Override
public void getBitmap(Context context, String url, final ImageListener<Bitmap> imageListener) {
    // 参考自https://github.com/hpdx/fresco-helper/blob/master/fresco-helper/src/main/java/com/facebook/fresco/helper/ImageLoader.java
    Uri uri = Uri.parse(url);
    ImagePipeline imagePipeline = Fresco.getImagePipeline();
    ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(uri);
    ImageRequest imageRequest = builder.build();
    DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
    dataSource.subscribe(new BaseDataSubscriber<CloseableReference<CloseableImage>>() {

        @Override
        public void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
            if (!dataSource.isFinished()) {
                return;
            }
            CloseableReference<CloseableImage> imageReference = dataSource.getResult();
            if (imageReference != null) {
                final CloseableReference<CloseableImage> closeableReference = imageReference.clone();
                try {
                    CloseableImage closeableImage = closeableReference.get();
                    // 动图处理
                    if (closeableImage instanceof CloseableAnimatedImage) {
                        AnimatedImageResult animatedImageResult = ((CloseableAnimatedImage) closeableImage).getImageResult();
                        if (animatedImageResult != null && animatedImageResult.getImage() != null) {
                            int imageWidth = animatedImageResult.getImage().getWidth();
                            int imageHeight = animatedImageResult.getImage().getHeight();
                            Bitmap.Config bitmapConfig = Bitmap.Config.ARGB_8888;
                            Bitmap bitmap = Bitmap.createBitmap(imageWidth, imageHeight, bitmapConfig);
                            animatedImageResult.getImage().getFrame(0).renderFrame(imageWidth, imageHeight, bitmap);
                            if (imageListener != null) {
                                imageListener.onSuccess(bitmap);
                            }
                        }
                    } else // 非动图处理
                    if (closeableImage instanceof CloseableBitmap) {
                        CloseableBitmap closeableBitmap = (CloseableBitmap) closeableImage;
                        Bitmap bitmap = closeableBitmap.getUnderlyingBitmap();
                        if (bitmap != null && !bitmap.isRecycled()) {
                            // https://github.com/facebook/fresco/issues/648
                            final Bitmap tempBitmap = bitmap.copy(bitmap.getConfig(), false);
                            if (imageListener != null) {
                                imageListener.onSuccess(tempBitmap);
                            }
                        }
                    }
                } finally {
                    imageReference.close();
                    closeableReference.close();
                }
            }
        }

        @Override
        public void onFailureImpl(DataSource dataSource) {
            Throwable throwable = dataSource.getFailureCause();
            if (imageListener != null) {
                imageListener.onFail(throwable);
            }
        }
    }, UiThreadImmediateExecutorService.getInstance());
}
Also used : CloseableAnimatedImage(com.facebook.imagepipeline.image.CloseableAnimatedImage) DiskCacheConfig(com.facebook.cache.disk.DiskCacheConfig) ImageConfig(com.ljy.devring.image.support.ImageConfig) ImagePipelineConfig(com.facebook.imagepipeline.core.ImagePipelineConfig) SimpleProgressiveJpegConfig(com.facebook.imagepipeline.decoder.SimpleProgressiveJpegConfig) CloseableReference(com.facebook.common.references.CloseableReference) AnimatedImageResult(com.facebook.imagepipeline.animated.base.AnimatedImageResult) CloseableImage(com.facebook.imagepipeline.image.CloseableImage) Uri(android.net.Uri) CloseableBitmap(com.facebook.imagepipeline.image.CloseableBitmap) DataSource(com.facebook.datasource.DataSource) CloseableBitmap(com.facebook.imagepipeline.image.CloseableBitmap) Bitmap(android.graphics.Bitmap) ImageRequest(com.facebook.imagepipeline.request.ImageRequest) ImagePipeline(com.facebook.imagepipeline.core.ImagePipeline) ImageRequestBuilder(com.facebook.imagepipeline.request.ImageRequestBuilder)

Example 2 with CloseableImage

use of com.facebook.imagepipeline.image.CloseableImage in project remusic by aa112901.

the class MediaService method getNotification.

private Notification getNotification() {
    RemoteViews remoteViews;
    final int PAUSE_FLAG = 0x1;
    final int NEXT_FLAG = 0x2;
    final int STOP_FLAG = 0x3;
    final String albumName = getAlbumName();
    final String artistName = getArtistName();
    final boolean isPlaying = isPlaying();
    remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);
    String text = TextUtils.isEmpty(albumName) ? artistName : artistName + " - " + albumName;
    remoteViews.setTextViewText(R.id.title, getTrackName());
    remoteViews.setTextViewText(R.id.text, text);
    // 此处action不能是一样的 如果一样的 接受的flag参数只是第一个设置的值
    Intent pauseIntent = new Intent(TOGGLEPAUSE_ACTION);
    pauseIntent.putExtra("FLAG", PAUSE_FLAG);
    PendingIntent pausePIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, 0);
    remoteViews.setImageViewResource(R.id.iv_pause, isPlaying ? R.drawable.note_btn_pause : R.drawable.note_btn_play);
    remoteViews.setOnClickPendingIntent(R.id.iv_pause, pausePIntent);
    Intent nextIntent = new Intent(NEXT_ACTION);
    nextIntent.putExtra("FLAG", NEXT_FLAG);
    PendingIntent nextPIntent = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.iv_next, nextPIntent);
    Intent preIntent = new Intent(STOP_ACTION);
    preIntent.putExtra("FLAG", STOP_FLAG);
    PendingIntent prePIntent = PendingIntent.getBroadcast(this, 0, preIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.iv_stop, prePIntent);
    // PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0,
    // new Intent(this.getApplicationContext(), PlayingActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    final Intent nowPlayingIntent = new Intent();
    // nowPlayingIntent.setAction("com.wm.remusic.LAUNCH_NOW_PLAYING_ACTION");
    nowPlayingIntent.setComponent(new ComponentName("com.wm.remusic", "com.wm.remusic.activity.PlayingActivity"));
    nowPlayingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent clickIntent = PendingIntent.getBroadcast(this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent click = PendingIntent.getActivity(this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    final Bitmap bitmap = ImageUtils.getArtworkQuick(this, getAlbumId(), 160, 160);
    if (bitmap != null) {
        remoteViews.setImageViewBitmap(R.id.image, bitmap);
        // remoteViews.setImageViewUri(R.id.image, MusicUtils.getAlbumUri(this, getAudioId()));
        mNoBit = null;
    } else if (!isTrackLocal()) {
        if (mNoBit != null) {
            remoteViews.setImageViewBitmap(R.id.image, mNoBit);
            mNoBit = null;
        } else {
            Uri uri = null;
            if (getAlbumPath() != null) {
                try {
                    uri = Uri.parse(getAlbumPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (getAlbumPath() == null || uri == null) {
                mNoBit = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_disk_210);
                updateNotification();
            } else {
                ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri).setProgressiveRenderingEnabled(true).build();
                ImagePipeline imagePipeline = Fresco.getImagePipeline();
                DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, MediaService.this);
                dataSource.subscribe(new BaseBitmapDataSubscriber() {

                    @Override
                    public void onNewResultImpl(@Nullable Bitmap bitmap) {
                        // No need to do any cleanup.
                        if (bitmap != null) {
                            mNoBit = bitmap;
                        }
                        updateNotification();
                    }

                    @Override
                    public void onFailureImpl(DataSource dataSource) {
                        // No cleanup required here.
                        mNoBit = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_disk_210);
                        updateNotification();
                    }
                }, CallerThreadExecutor.getInstance());
            }
        }
    } else {
        remoteViews.setImageViewResource(R.id.image, R.drawable.placeholder_disk_210);
    }
    if (mNotificationPostTime == 0) {
        mNotificationPostTime = System.currentTimeMillis();
    }
    if (mNotification == null) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContent(remoteViews).setSmallIcon(R.drawable.ic_notification).setContentIntent(click).setWhen(mNotificationPostTime);
        if (CommonUtils.isJellyBeanMR1()) {
            builder.setShowWhen(false);
        }
        mNotification = builder.build();
    } else {
        mNotification.contentView = remoteViews;
    }
    return mNotification;
}
Also used : ImageRequestBuilder(com.facebook.imagepipeline.request.ImageRequestBuilder) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) CloseableImage(com.facebook.imagepipeline.image.CloseableImage) Uri(android.net.Uri) SuppressLint(android.annotation.SuppressLint) FileNotFoundException(java.io.FileNotFoundException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) DataSource(com.facebook.datasource.DataSource) BaseBitmapDataSubscriber(com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber) RemoteViews(android.widget.RemoteViews) Bitmap(android.graphics.Bitmap) ImageRequest(com.facebook.imagepipeline.request.ImageRequest) NotificationCompat(android.support.v4.app.NotificationCompat) ComponentName(android.content.ComponentName) PendingIntent(android.app.PendingIntent) ImagePipeline(com.facebook.imagepipeline.core.ImagePipeline) Nullable(android.support.annotation.Nullable)

Example 3 with CloseableImage

use of com.facebook.imagepipeline.image.CloseableImage in project fresco by facebook.

the class AnimatedRepeatedPostprocessorProducerTest method testNonStaticBitmapIsPassedOn.

@Test
public void testNonStaticBitmapIsPassedOn() {
    RepeatedPostprocessorConsumer postprocessorConsumer = produceResults();
    RepeatedPostprocessorRunner repeatedPostprocessorRunner = getRunner();
    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.NO_FLAGS));
    mInOrder.verifyNoMoreInteractions();
    assertEquals(1, mResults.size());
    CloseableReference<CloseableImage> res0 = mResults.get(0);
    assertTrue(CloseableReference.isValid(res0));
    assertSame(sourceCloseableAnimatedImage, res0.get());
    res0.close();
    performCancelAndVerifyOnCancellation();
    verify(sourceCloseableAnimatedImage).close();
}
Also used : RepeatedPostprocessorConsumer(com.facebook.imagepipeline.producers.PostprocessorProducer.RepeatedPostprocessorConsumer) CloseableAnimatedImage(com.facebook.imagepipeline.image.CloseableAnimatedImage) CloseableReference(com.facebook.common.references.CloseableReference) CloseableImage(com.facebook.imagepipeline.image.CloseableImage) RepeatedPostprocessorRunner(com.facebook.imagepipeline.request.RepeatedPostprocessorRunner)

Example 4 with CloseableImage

use of com.facebook.imagepipeline.image.CloseableImage in project fresco by facebook.

the class LocalThumbnailBitmapProducer method produceResults.

@Override
public void produceResults(final Consumer<CloseableReference<CloseableImage>> consumer, final ProducerContext context) {
    final ProducerListener2 listener = context.getProducerListener();
    final ImageRequest imageRequest = context.getImageRequest();
    context.putOriginExtra("local", "thumbnail_bitmap");
    final CancellationSignal cancellationSignal = new CancellationSignal();
    final StatefulProducerRunnable<CloseableReference<CloseableImage>> cancellableProducerRunnable = new StatefulProducerRunnable<CloseableReference<CloseableImage>>(consumer, listener, context, PRODUCER_NAME) {

        @Override
        protected void onSuccess(@Nullable CloseableReference<CloseableImage> result) {
            super.onSuccess(result);
            listener.onUltimateProducerReached(context, PRODUCER_NAME, result != null);
            context.putOriginExtra("local");
        }

        @Override
        protected void onFailure(Exception e) {
            super.onFailure(e);
            listener.onUltimateProducerReached(context, PRODUCER_NAME, false);
            context.putOriginExtra("local");
        }

        @Override
        @Nullable
        protected CloseableReference<CloseableImage> getResult() throws IOException {
            final Bitmap thumbnailBitmap = mContentResolver.loadThumbnail(imageRequest.getSourceUri(), new Size(imageRequest.getPreferredWidth(), imageRequest.getPreferredHeight()), cancellationSignal);
            if (thumbnailBitmap == null) {
                return null;
            }
            CloseableStaticBitmap closeableStaticBitmap = new CloseableStaticBitmap(thumbnailBitmap, SimpleBitmapReleaser.getInstance(), ImmutableQualityInfo.FULL_QUALITY, 0);
            context.setExtra(ProducerContext.ExtraKeys.IMAGE_FORMAT, "thumbnail");
            closeableStaticBitmap.setImageExtras(context.getExtras());
            return CloseableReference.<CloseableImage>of(closeableStaticBitmap);
        }

        @Override
        protected void onCancellation() {
            super.onCancellation();
            cancellationSignal.cancel();
        }

        @Override
        protected Map<String, String> getExtraMapOnSuccess(@Nullable final CloseableReference<CloseableImage> result) {
            return ImmutableMap.of(CREATED_THUMBNAIL, String.valueOf(result != null));
        }

        @Override
        protected void disposeResult(CloseableReference<CloseableImage> result) {
            CloseableReference.closeSafely(result);
        }
    };
    context.addCallbacks(new BaseProducerContextCallbacks() {

        @Override
        public void onCancellationRequested() {
            cancellableProducerRunnable.cancel();
        }
    });
    mExecutor.execute(cancellableProducerRunnable);
}
Also used : Size(android.util.Size) CloseableReference(com.facebook.common.references.CloseableReference) CloseableImage(com.facebook.imagepipeline.image.CloseableImage) IOException(java.io.IOException) Bitmap(android.graphics.Bitmap) CloseableStaticBitmap(com.facebook.imagepipeline.image.CloseableStaticBitmap) ImageRequest(com.facebook.imagepipeline.request.ImageRequest) CloseableStaticBitmap(com.facebook.imagepipeline.image.CloseableStaticBitmap) CancellationSignal(android.os.CancellationSignal) Nullable(javax.annotation.Nullable)

Example 5 with CloseableImage

use of com.facebook.imagepipeline.image.CloseableImage in project fresco by facebook.

the class BitmapMemoryCacheProducer method wrapConsumer.

protected Consumer<CloseableReference<CloseableImage>> wrapConsumer(final Consumer<CloseableReference<CloseableImage>> consumer, final CacheKey cacheKey, final boolean isBitmapCacheEnabledForWrite) {
    return new DelegatingConsumer<CloseableReference<CloseableImage>, CloseableReference<CloseableImage>>(consumer) {

        @Override
        public void onNewResultImpl(@Nullable CloseableReference<CloseableImage> newResult, @Status int status) {
            try {
                if (FrescoSystrace.isTracing()) {
                    FrescoSystrace.beginSection("BitmapMemoryCacheProducer#onNewResultImpl");
                }
                final boolean isLast = isLast(status);
                // ignore invalid intermediate results and forward the null result if last
                if (newResult == null) {
                    if (isLast) {
                        getConsumer().onNewResult(null, status);
                    }
                    return;
                }
                // stateful and partial results cannot be cached and are just forwarded
                if (newResult.get().isStateful() || statusHasFlag(status, IS_PARTIAL_RESULT)) {
                    getConsumer().onNewResult(newResult, status);
                    return;
                }
                // forward the already cached result and don't cache the new result.
                if (!isLast) {
                    CloseableReference<CloseableImage> currentCachedResult = mMemoryCache.get(cacheKey);
                    if (currentCachedResult != null) {
                        try {
                            QualityInfo newInfo = newResult.get().getQualityInfo();
                            QualityInfo cachedInfo = currentCachedResult.get().getQualityInfo();
                            if (cachedInfo.isOfFullQuality() || cachedInfo.getQuality() >= newInfo.getQuality()) {
                                getConsumer().onNewResult(currentCachedResult, status);
                                return;
                            }
                        } finally {
                            CloseableReference.closeSafely(currentCachedResult);
                        }
                    }
                }
                // cache, if needed, and forward the new result
                CloseableReference<CloseableImage> newCachedResult = null;
                if (isBitmapCacheEnabledForWrite) {
                    newCachedResult = mMemoryCache.cache(cacheKey, newResult);
                }
                try {
                    if (isLast) {
                        getConsumer().onProgressUpdate(1f);
                    }
                    getConsumer().onNewResult((newCachedResult != null) ? newCachedResult : newResult, status);
                } finally {
                    CloseableReference.closeSafely(newCachedResult);
                }
            } finally {
                if (FrescoSystrace.isTracing()) {
                    FrescoSystrace.endSection();
                }
            }
        }
    };
}
Also used : CloseableReference(com.facebook.common.references.CloseableReference) CloseableImage(com.facebook.imagepipeline.image.CloseableImage) QualityInfo(com.facebook.imagepipeline.image.QualityInfo) Nullable(javax.annotation.Nullable)

Aggregations

CloseableImage (com.facebook.imagepipeline.image.CloseableImage)28 CloseableReference (com.facebook.common.references.CloseableReference)13 CacheKey (com.facebook.cache.common.CacheKey)7 ImageRequest (com.facebook.imagepipeline.request.ImageRequest)7 Bitmap (android.graphics.Bitmap)6 CloseableBitmap (com.facebook.imagepipeline.image.CloseableBitmap)4 Nullable (javax.annotation.Nullable)4 Drawable (android.graphics.drawable.Drawable)3 ImagePipeline (com.facebook.imagepipeline.core.ImagePipeline)3 CloseableAnimatedImage (com.facebook.imagepipeline.image.CloseableAnimatedImage)3 CloseableStaticBitmap (com.facebook.imagepipeline.image.CloseableStaticBitmap)3 IOException (java.io.IOException)3 Before (org.junit.Before)3 Uri (android.net.Uri)2 SimpleCacheKey (com.facebook.cache.common.SimpleCacheKey)2 DataSource (com.facebook.datasource.DataSource)2 ScaleTypeDrawable (com.facebook.drawee.drawable.ScaleTypeDrawable)2 BitmapMemoryCacheKey (com.facebook.imagepipeline.cache.BitmapMemoryCacheKey)2 CountingMemoryCacheInspector (com.facebook.imagepipeline.cache.CountingMemoryCacheInspector)2 QualityInfo (com.facebook.imagepipeline.image.QualityInfo)2