Skip to content

Commit

Permalink
Improve image retrieval from Coil memory/disk caches
Browse files Browse the repository at this point in the history
  • Loading branch information
Isira-Seneviratne committed Jul 22, 2024
1 parent 7c83a42 commit 7d92a1d
Showing 1 changed file with 23 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
Expand All @@ -27,9 +28,9 @@
import org.schabi.newpipe.util.image.ImageStrategy;

import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import coil.Coil;
import coil.disk.DiskCache;
Expand Down Expand Up @@ -377,33 +378,36 @@ private static ClipData generateClipDataForImagePreview(
// Save the image in memory to the application's cache because we need a URI to the
// image to generate a ClipData which will show the share sheet, and so an image file
final Context applicationContext = context.getApplicationContext();
final var appFolder = applicationContext.getCacheDir().toPath();
final var preview = appFolder.resolve("android_share_sheet_image_preview.jpg");

final var loader = Coil.imageLoader(context);
final var value = loader.getMemoryCache()
.get(new MemoryCache.Key(thumbnailUrl, Collections.emptyMap()));
final var cachedBitmap = Optional.ofNullable(value)
.map(MemoryCache.Value::getBitmap)
.orElseGet(() -> {
try (var snapshot = loader.getDiskCache().openSnapshot(thumbnailUrl)) {
if (snapshot != null) {
return BitmapFactory.decodeFile(snapshot.getData().toString());
} else {
return null;
}
}
});

if (cachedBitmap == null) {
return null;
}

if (value != null) {
// Any existing file will be overwritten
try (var outputStream = Files.newOutputStream(preview)) {
value.getBitmap().compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}
} else {
try (var snapshot = loader.getDiskCache().openSnapshot(thumbnailUrl)) {
if (snapshot != null) {
final var path = snapshot.getData().toNioPath();
Files.copy(path, preview, StandardCopyOption.REPLACE_EXISTING);
} else {
return null;
}
}
final var path = applicationContext.getCacheDir().toPath()
.resolve("android_share_sheet_image_preview.jpg");
// Any existing file will be overwritten
try (var outputStream = Files.newOutputStream(path)) {
cachedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
}

final ClipData clipData = ClipData.newUri(applicationContext.getContentResolver(), "",
FileProvider.getUriForFile(applicationContext,
BuildConfig.APPLICATION_ID + ".provider",
preview.toFile()));
path.toFile()));

if (DEBUG) {
Log.d(TAG, "ClipData successfully generated for Android share sheet: " + clipData);
Expand Down

0 comments on commit 7d92a1d

Please sign in to comment.