Skip to content

Instantly share code, notes, and snippets.

@romansl
Created December 28, 2015 08:50
Show Gist options
  • Save romansl/183a96ddf89bd52284cc to your computer and use it in GitHub Desktop.
Save romansl/183a96ddf89bd52284cc to your computer and use it in GitHub Desktop.
VideoImageDownloader downloader for UIL
public class VideoImageDownloader extends BaseImageDownloader {
public AnyImageDownloader(Context context) {
super(context);
}
@Override
protected InputStream getStreamFromContent(final String imageUri, final Object extra) throws FileNotFoundException {
final ContentResolver res = context.getContentResolver();
final Uri uri = Uri.parse(imageUri);
final String type = res.getType(uri);
if (type != null && type.startsWith("video/")) {
return getVideoThumbnail(uri);
} else {
return res.openInputStream(uri);
}
}
@Override
protected InputStream getStreamFromFile(final String imageUri, final Object extra) throws IOException {
if (imageUri.endsWith(".mp4")) {
return getVideoThumbnail(Uri.parse(imageUri));
} else {
return super.getStreamFromFile(imageUri, extra);
}
}
private InputStream getVideoThumbnail(final Uri uri) {
try {
final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
Bitmap thumbnail = null;
OutputStream os = null;
try {
thumbnail = VideoUtilsKt.createVideoThumbnail(context, uri, 256);
os = new FileOutputStream(fds[1].getFileDescriptor());
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, os);
} catch (Exception ignored) {
} finally {
if (thumbnail != null) {
thumbnail.recycle();
}
if (os != null) {
try {
os.close();
} catch (Exception ignored) {
}
}
try {
fds[1].close();
} catch (Exception ignored) {
}
}
}
});
return new FileInputStream(fds[0].getFileDescriptor());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public fun createVideoThumbnail(context: Context, uri: Uri, maxSize: Int): Bitmap {
val bitmap = getFirstFrame(context, uri)
val width = bitmap.width
val height = bitmap.height
val max = Math.max(width, height)
if (max > maxSize) {
val scale = maxSize.toFloat() / max
val w = Math.round(scale * width)
val h = Math.round(scale * height)
try {
return Bitmap.createScaledBitmap(bitmap, w, h, true)
} catch (e: OutOfMemoryError) {
throw RuntimeException(e)
} finally {
bitmap.recycle()
}
}
return bitmap
}
public fun getFirstFrame(context: Context, uri: Uri): Bitmap {
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(context, uri)
return retriever.getFrameAtTime(-1)
} catch (e: OutOfMemoryError) {
throw RuntimeException(e)
} finally {
try {
retriever.release()
} catch (ignored: Exception) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment