前言:期待已久的周末终于到来了,虽然明天还需要上班,但是今天却不像平日里迫切的赶回家。饭后,闲来无事结合最近的一个项目需求,编写一个小demo,主要是实现视频文件缩略图的获取。
我的思路是,首先获取所有的视频文件列表,然后依次获取缩略图并展示。但是出于时间因素,在这里我只获取第一个视频文件的缩略图,也就是这个demo的流程大致为“获取视频列表—获取第一个视频的缩略图展示—保存缩略图至本地”。
关键代码:
1、利用Glide获取视频缩略图
Glide.with(this).load(video.getUrl1()).asBitmap().placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher).into(target);
2、获取视频列表
public List<Video> getVideos() { List<Video> list = null; if (this != null) { Cursor cursor = getContentResolver().query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, null); if (cursor != null) { list = new ArrayList<Video>(); while (cursor.moveToNext()) { int id = cursor.getInt(cursor .getColumnIndexOrThrow(MediaStore.Video.Media._ID)); String title = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.TITLE)); String album = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM)); String artist = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST)); String displayName = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)); String mimeType = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE)); String path = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DATA)); long duration = cursor .getInt(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)); long size = cursor .getLong(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)); Video video = new Video(); video.setName1(title); video.setSize1(size); video.setUrl1(path); video.setDuration1(duration); list.add(video); } cursor.close(); } } return list; }
3、保存图片
public String savePhoto(Bitmap photoBitmap,String photoName) { String path = ""; String localPath = null; path = Environment.getExternalStorageDirectory()+"/"+photoName+".png"; File photoFile = new File(path); if (photoFile.exists()){ photoFile.mkdirs(); } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(photoFile); if (photoBitmap != null) { if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) { localPath = photoFile.getPath(); fileOutputStream.flush(); Toast.makeText(MainActivity.this,"图片成功保存至:"+localPath,Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(MainActivity.this,"Bitmap为空",Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException e) { photoFile.delete(); localPath = null; e.printStackTrace(); Log.e("saveerror","FileNotFound"); } catch (IOException e) { photoFile.delete(); localPath = null; Log.e("saveerror",e.getMessage()); e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); fileOutputStream = null; } } catch (IOException e) { e.printStackTrace(); } } return localPath; }
注意事项:
由于Glide是异步加载,如果采用ImageView截图的方式来获得缩略图,可能会出现空指针的问题,为了解决这一问题,Glide的into对象并不是ImageView,而是自定义的一个SimpleTarget,在onResourceReady中处理bitmap并且保存