Android必知必會-擷取視頻檔案的、縮圖
背景
公司最近要求給我負責的APP加上視頻錄製和發布的功能,我簡單的完成了基本的錄製和視頻壓縮功能,後來發現發布介面需要上傳視頻的,網上搜尋了一下資料,在這裡整理一下。
代碼實現
/** * 擷取視頻檔案 * * @param path 視頻檔案的路徑 * @return Bitmap 返回擷取的Bitmap */ public static Bitmap getVideoThumb(String path) { MediaMetadataRetriever media = new MediaMetadataRetriever(); media.setDataSource(path); return media.getFrameAtTime(); } /** * 擷取視頻檔案縮圖 API>=8(2.2) * * @param path 視頻檔案的路徑 * @param kind 縮圖的解析度:MINI_KIND、MICRO_KIND、FULL_SCREEN_KIND * @return Bitmap 返回擷取的Bitmap */ public static Bitmap getVideoThumb2(String path, int kind) { return ThumbnailUtils.createVideoThumbnail(path, kind); } public static Bitmap getVideoThumb2(String path) { return getVideoThumb2(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND); }
以上是擷取視頻檔案的和縮圖的方法,你可能還需要把Bitmap儲存成檔案:
/** * Bitmap儲存成File * * @param bitmap input bitmap * @param name output file's name * @return String output file's path */ public static String bitmap2File(Bitmap bitmap, String name) { File f = new File(Environment.getExternalStorageDirectory() + name + ".jpg"); if (f.exists()) f.delete(); FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); fOut.flush(); fOut.close(); } catch (IOException e) { return null; } return f.getAbsolutePath(); }
參考和總結
以上是自己搜集整理的一點資料,沒有進行多方面的比較和深層次的分析(API版本限制等等),使用中有什麼問題歡迎留言。