android调用相机录像保存并生成缩略图

1.权限申请参考https://blog.csdn.net/chailongger/article/details/104833783

2.

private static final int TAKEVIDEO_FORESULT = 1001;
private String videoPath;//视频保存后的路径
/**
 * 调用相机录像
 */
private void takeVideo(){
    Intent intent=new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    Uri fileUri;
    try {
        //fileUri=Uri.fromFile(createMediaFile());如果这样写会报错
        fileUri=         FileProvider.getUriForFile(getContext(),getActivity().getApplicationContext().getPackageName() + ".provider",createMediaFile());//这是正确的写法
        intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);
        Logs.i("fileUri "+fileUri.toString());
        Logs.i("打开录像机");
    } catch (IOException e) {
        e.printStackTrace();
    }

    //质量
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
    //限制时长
    intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5);
    //限制大小
    intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024*1024*20L);

    startActivityForResult(intent,TAKEVIDEO_FORESULT);
}


@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == TAKEVIDEO_FORESULT && resultCode == -1){//resultCode == 0 时表示取消
        Logs.i("调用相机录像并保存");
        if(videoPath != null){
        Logs.i("videoPath "+videoPath);
        //生成视频的缩略图
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND);

        videoPath = videoPath.replace("/storage/emulated/0","");
        videoPath = videoPath.replace("Video","Camera");
        videoPath = videoPath.replace(".mp4",".jpg");
        Logs.i("filepath " +videoPath);
        File file = ConvertUtil.compressImage(bitmap,videoPath);
        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

        ImageItem imageItem = new ImageItem();
        imageItem.path = Environment.getExternalStorageDirectory()+videoPath;
        selImageList.add(imageItem);
        adapter.setImages(selImageList);

    }
}


//创建并保存视频的方法
private File createMediaFile() throws IOException {
    if(checkSDCardAvaliable()) {
    if ((Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
        // 选择自己的文件夹
        String path = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Video/";
        File mediaStorageDir = new File(path);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Logs.i("文件夹创建失败");
                return null;
            }
        }

        // 文件根据当前的时间给自己命名
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
       String imageFileName = "VID_" + dateFormat.format(new Date(System.currentTimeMillis()));
       String suffix = ".mp4";
       Logs.i("path "+mediaStorageDir + File.separator + imageFileName + suffix);
       videoPath = mediaStorageDir + File.separator + imageFileName + suffix;
       File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix);
       return mediaFile;
       }
    }
    return null;
}

/**
 * 检查sd卡是否可用
 *
 * @return
 */
public static boolean checkSDCardAvaliable() {
    if (Environment.getExternalStorageState() == Environment.MEDIA_REMOVED) {
        return false;
    }
    return true;
}

转换工具类

/**
 * 转换工具类
 * 1. string转成bitmap
 * 2. bitmap转file
 */
public class ConvertUtil {
    /** * string转成bitmap *  * @param st */
    public static Bitmap convertStringToIcon(String st) {
        Bitmap bitmap = null;
        try {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        } catch (Exception e) { return null; }
    }

    public static File compressImage(Bitmap bitmap,String filepath) {

        //将要保存图片的路径filepath
        File file = new File(Environment.getExternalStorageDirectory(), filepath);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//            uploadPic(file);
            bos.flush();
            bos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;

    }

}

在applicationmanifest中添加fileprovider,android6.0以后读取或保存文件时需要用fileProvider进行转换。

<application>
    <provider
        android:authorities="${applicationId}.provider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths">
        </meta-data>
    </provider>
</application>

provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!--<external-path name="external_files" path="."/>-->

    <!-- 物理路径为Context.getFilesDir() + /files/* -->
    <files-path path="." name="files" />
    <!-- 物理路径为Context.getCacheDir() + /files/* -->
    <cache-path path="." name="cache" />
    <!-- 物理路径为Environment.getExternalStorageDirectory() + /files/* -->
    <external-path path="." name="external" />
    <!-- 物理路径为Context.getExternalFilesDir(String) + /files/* -->
    <external-files-path path="." name="externalfiles"/>
    <!-- 物理路径为Context.getExternalCacheDir() + /files/* -->
    <external-cache-path  path="." name="externalcache"/>
    <!-- 物理路径为`Context.getExternalMediaDirs() + /files/*, 要求API21+ -->
    <external-media-path name="." path="files" />
</paths>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chailongger

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值