近期做的留言板功能,有从本地选取图片或视频发送到留言板的功能:
点击主页面的图片按钮:
case R.id.ll_pic:
if (!PermissionHelper.checkPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)) {
ToastUtils.showShort(mContext, String.format(getString(R.string.permission_help_text), getString(R.string.per_storage)));
return;
}
Intent intentPic = new Intent(
Intent.ACTION_GET_CONTENT);
intentPic.addCategory(Intent.CATEGORY_OPENABLE);
intentPic.setType("video/*;image/*");
startActivityForResult(intentPic,
RESULT_LOAD_IMAGE);
break;
选中图片或视频之后的接收处理:视频只支持1分钟以下的mp4文件
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case RESULT_LOAD_IMAGE://从图库选择照片返回的路径 try { String filePath = null; Uri originalUri = data.getData(); int size = 0; if (originalUri.toString().startsWith("file://")) { filePath = originalUri.getPath(); camerPath = filePath; if (!filePath.endsWith(".jpg") && !filePath.endsWith(".png") && !filePath.endsWith(".jpeg") && !filePath.endsWith(".mp4")) { Toast.makeText(MainMessageBoard.this,"不支持该格式",Toast.LENGTH_SHORT).show(); return; } } else { // String[] projection = {MediaStore.Images.Media.DATA}; // Cursor cursor = getContentResolver().query(originalUri, // projection, null, null, null); // int column_index = cursor // .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // cursor.moveToFirst(); // filePath = cursor.getString(column_index); Cursor cursor = getContentResolver().query(originalUri, null, null, null, null); cursor.moveToFirst(); LogUtil.d(TAG, "" + cursor.getString(0) + "," + cursor.getString(1) + "," + cursor.getString(2)); filePath = cursor.getString(1); camerPath = filePath; if (camerPath.endsWith(".mp4")) { // size = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.SIZE)); size = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.DURATION)); } if (filePath == null) { //android 4.4取最近使用的图片 String wholeID = DocumentsContract .getDocumentId(originalUri); String id = wholeID.split(":")[1]; String[] column = {MediaStore.Images.Media.DATA}; String sel = MediaStore.Images.Media._ID + "=?"; cursor = getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { filePath = cursor.getString(columnIndex); camerPath = filePath; } cursor.close(); } } // Uri uri = Uri.fromFile(new File(filePath)); // startPhotoZoom(uri); if (camerPath.endsWith(".mp4")) { size = Integer.valueOf(MsgUtil.getDuration(camerPath)); String videoArray[] = camerPath.split("/"); videoname = videoArray[videoArray.length - 1]; msgType = 3; if (size <= 60 * 1000) { head_img_name = System.currentTimeMillis() + ".jpg"; MsgUtil.saveFile(MsgUtil.getVideoThumbnail(camerPath), head_img_name); thumbnail = MsgUtil.ALBUM_PATH + head_img_name; isMsg = 1;//0可以用于发送文字,图片 语音 1:用于发送视频缩略图 2:用于发送视频文件 insertMsg(); if(!deviceMac.equals("Virtual")){ DialogHelper.showRoundProcessDialog(MainMessageBoard.this,"正在加载中",true); sendFileToAliyun("leaveMsg/" + sdf.format(new Date()) + "/" + head_img_name, thumbnail); } // sendFileToAliyun("leaveMsg/" + sdf.format(new Date()) + "/" + videoname, camerPath); // sendVideoMsg(); } else { Toast.makeText(mContext, "只支持上传1分钟之内的视频", Toast.LENGTH_SHORT).show(); } } else if (camerPath.endsWith(".3gp")) { Toast.makeText(mContext, "只支持mp4格式", Toast.LENGTH_SHORT).show(); } else { String picArray[] = camerPath.split("/"); fileName = picArray[picArray.length - 1]; isMsg = 0;//0可以用于发送文字,图片 语音 1:用于发送视频 msgType = 1; insertMsg(); if(!deviceMac.equals("Virtual")){ DialogHelper.showRoundProcessDialog(MainMessageBoard.this,"正在加载中",true); sendFileToAliyun("leaveMsg/" + sdf.format(new Date()) + "/" + fileName, camerPath); } // sendPicMsg(); } } catch (Exception ex) { ex.printStackTrace(); } break; case 10: if (data != null) { // int da = data.getIntExtra("data",0); // if(da == 1){ // queryMsg(); // } MsgBoard msgBoard = (MsgBoard) data.getSerializableExtra("data"); if (msgBoardList != null && msgBoardList.size() > 0) { msgBoardList.add(0, msgBoard); } else { msgBoardList = new ArrayList(); msgBoardList.add(msgBoard); } newAdapter.setList(msgBoardList); messageList.setAdapter(newAdapter); newAdapter.notifyDataSetChanged(); if (msgBoardList != null && msgBoardList.size() > 0) { noMessageRel.setVisibility(View.GONE); messageList.setVisibility(View.VISIBLE); // refresh_msg.setVisibility(View.VISIBLE); } else { noMessageRel.setVisibility(View.VISIBLE); messageList.setVisibility(View.GONE); // refresh_msg.setVisibility(View.INVISIBLE); } MsgBoadDao.insertData(msgBoard); } break; } } else { camerPath = ""; } }
其中
RESULT_LOAD_IMAGE是选中图片或视频后的处理,10是从单独的画板界面返回后的处理,画板界面返回了一个MsgBoard
获取视频缩略图和时长的公共方法:
package com.haier.uhome.appliance.newVersion.module.messageboard.view; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.media.ExifInterface; import android.media.MediaMetadataRetriever; import android.os.Environment; import com.haier.uhome.application.HaierApp; import com.haier.uhome.common.util.LogUtil; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by wangchm on 2017/1/25 0025. */ public class MsgUtil { public static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/download_img/"; //得到视频缩略图 public static Bitmap getVideoThumbnail(String filePath) { Bitmap bitmap = null; MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(filePath); bitmap = retriever.getFrameAtTime(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } finally { try { retriever.release(); } catch (RuntimeException e) { e.printStackTrace(); } } return bitmap; } //获取视频时长 public static String getDuration(String path){ String duration; MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(path); duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); return duration; } //保存图片到本地 public static void saveFile(Bitmap bm, String imgName) { File dirFile = new File(ALBUM_PATH); if (!dirFile.exists()) { dirFile.mkdir(); } File myFile = new File(ALBUM_PATH + imgName); try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myFile)); bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); } catch (Exception ex) { ex.printStackTrace(); } } }