1.项目中使用listView展示SD卡中所有的视频,原来是需要手动添加路径,特别麻烦,有的外置卡什么的会读取不到,所以重新对方法进行了修改。
2.在adapter中设置图片的时候:
mViewHolder.videoView.setImageBitmap(bitmapCache.getVideoThumbnail(mContext,url, 500, 300, MediaStore.Images.Thumbnails.MICRO_KIND));
url = localPath.get(position);
3.数据来源:获取所有视频地址的方法。获取的数据添加到adapter 中的List<String> localPath;
private static List<String> list = new ArrayList<String>(); private String[] strings; public String[] getPaths() { if (list != null) { list.clear(); } if (getContext() != null) { Cursor cursor = getActivity().getContentResolver().query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER); if (cursor != null) { while (cursor.moveToNext()) { String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)); list.add(path); } cursor.close(); } } if (list.size() != 0) { strings = list.toArray(new String[list.size()]); } return strings; }
4.方法调用:
主要就是获取地址最后的"/"以及"."中间的名称命名为".jpg“。 如果没有就从新保存一次图片。有的视频可能解码的时候没有图片,这是需要设置默认一张图。
public static Bitmap getVideoThumbnail(Context context, String videoPath, int width, int height, int kind) { Bitmap bitmap = null; int start = videoPath.lastIndexOf("/") + 1; String path = SdcardHelper.SDCARD_DIR + videoPath.substring(start, videoPath.lastIndexOf(".")) + ".jpg"; bitmap = getBitmap(path,width, height); if (bitmap == null) { bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind); bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT); if (bitmap == null) { bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.film_cover_loading1); } else { saveBitmap(bitmap, videoPath.substring(start, videoPath.lastIndexOf("."))); } } return bitmap; }
// 从SD卡中加载图片 public static Bitmap getBitmap(String path,int width, int height) { File mfile = new File(path); Bitmap bm = null; if (mfile.exists()) { Options options = new Options(); options.inJustDecodeBounds = true; options.inPurgeable = true; BitmapFactory.decodeFile(path, options); options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; bm = BitmapFactory.decodeFile(path, options); } return bm; }// 保存图片 private static File f; public static void saveBitmap(Bitmap bitmap, String picName) { f = new File(SdcardHelper.SDCARD_DIR, picName + ".jpg"); try { FileOutputStream out = new FileOutputStream(f); bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }