Android 獲取視訊(本地和網路)縮圖的解決方案
阿新 • • 發佈:2019-01-26
在Android 開發視訊的時候,通常都需要顯示視訊列表,而視訊列表通常都有一張視訊縮圖,那麼它是怎麼獲取的呢,
關於網路視訊的縮圖的實現方案主要有兩種:
1、後臺返回視訊時順便連縮圖的路徑都返回給你了,這樣前端壓力輕鬆。
2、後臺是返回視訊路徑,關於縮圖,前端從視訊中獲取。
那麼如何從視訊中獲取縮圖呢?
1、關於本地視訊的縮圖,官方有提供解決方案:
ThumbnailUtils.createVideoThumbnail(String filePath, int kind);
方法便可以獲取:
Bitmap bitmap= BitmapUtil.createVideoThumbnail(url,MediaStore.Video.Thumbnails.MINI_KIND);
2、那麼網路視訊怎麼獲取呢?
經過分析MediaMetadataRetriever類,發現有一個方法,setDataSource(String uri, Map
/**
* Sets the data source (URI) to use. Call this
* method before the rest of the methods in this class. This method may be
* time-consuming.
*
* @param uri The URI of the input media.
* @param headers the headers to be sent together with the request for the data
* @throws IllegalArgumentException If the URI is invalid.
*/
public void setDataSource(String uri, Map<String, String> headers)
throws IllegalArgumentException {
int i = 0;
String[] keys = new String[headers.size()];
String [] values = new String[headers.size()];
for (Map.Entry<String, String> entry: headers.entrySet()) {
keys[i] = entry.getKey();
values[i] = entry.getValue();
++i;
}
_setDataSource(
MediaHTTPService.createHttpServiceBinderIfNecessary(uri),
uri,
keys,
values);
}
這個方法說明了是獲取網路的資料,瞭解了原始碼就好辦,我們就依葫蘆畫瓢,自己建立一個類模仿一個方法出來:
這個方法,呼叫了retriever.setDataSource(filePath,new Hashtable
/**
* Create a video thumbnail for a video. May return null if the video is
* corrupt or the format is not supported.
*
* @param filePath the path of video file
* @param kind could be MINI_KIND or MICRO_KIND
*/
public static Bitmap createVideoThumbnail(String filePath, int kind) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
if (filePath.startsWith("http://")
|| filePath.startsWith("https://")
|| filePath.startsWith("widevine://")) {
retriever.setDataSource(filePath,new Hashtable<String, String>());
}else {
retriever.setDataSource(filePath);
}
bitmap = retriever.getFrameAtTime(-1);
} catch (IllegalArgumentException ex) {
// Assume this is a corrupt video file
ex.printStackTrace();
} catch (RuntimeException ex) {
// Assume this is a corrupt video file.
ex.printStackTrace();
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
ex.printStackTrace();
}
}
if (bitmap == null) return null;
if (kind == MediaStore.Images.Thumbnails.MINI_KIND) {
// Scale down the bitmap if it's too large.
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int max = Math.max(width, height);
if (max > 512) {
float scale = 512f / max;
int w = Math.round(scale * width);
int h = Math.round(scale * height);
bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
}
} else if (kind == MediaStore.Images.Thumbnails.MICRO_KIND) {
bitmap = ThumbnailUtils.extractThumbnail(bitmap,
96,
96,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
}
return bitmap;
}
這樣就可以獲取網路視訊縮圖了,可能還存在版本相容上沒做相容,歡迎提出意見