七牛云上传图片和视频

先说本文主要的重点:

七牛云上传图片(包括从相机获取的和从相册获取的)    七牛云上传视频       8.0手机调起相机        都会进行描述    多图片和多视频上传    获取图片后缀   隐藏软键盘

1、导入七牛云的依赖

 //七牛云
    api 'com.qiniu:qiniu-android-sdk:7.3.+'
    api 'pub.devrel:easypermissions:0.4.3'
    api 'com.qiniu:happy-dns:0.2.13'
    api 'com.loopj.android:android-async-http:1.4.9'

2、添加七牛云的工具类

https://download.csdn.net/download/jing_80/10832747     可以下载,我已上传

3、因为出于保护数据   所以中间的字符用xxxxx代替,这两个变量在七牛云上可以获取到,这个很重要,这个是获取七牛云Token需要用到的,不过我们这里的token是我们的后台返给我的,所以各位小伙伴看情况而定

    public static final String AccessKey = "-lOgC9xxxxxxxxxxxxiHIBDSrIZ";
    public static final String SecretKey = "PYCGWxxxxxxxxxxxxxxxKw0F0v0B0Sty4m";

4、前面的准备工作做完之后,来吧,接下来我们要写真正的上传代码了,一步一步来

如果你是准备好了相机相册各种权限的 就不说了   直接看(2)

如果你是什么也没写,那就先添加上调用相机所用的权限吧! 先看(1)

(1)在res下创建xml文件

xml文件中的内容:

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

再在AndroidManifest中添加代码和权限    权限可能不够    需要什么再添加

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-feature android:name="android.hardware.camera" />
    <!-- 相机权限 -->
    <uses-permission android:name="android.permission.CAMERA" />
    <!-- 写入SD卡的权限:如果你希望保存相机拍照后的照片 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 读取SD卡的权限:打开相册选取图片所必须的权限 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

在AndroidManifest中添加  这个provider和activity同级的

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

(2)七牛云上传代码

public class UploadDynamicActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_VIDEO = 0x00000012;
    private static final int REQUEST_CODE_CAMERA = 0x00000011;
    private static final int REQUEST_CODE_ALBUM = 0x00000010;
    private String upPath,videoThumb;
    private String headpicPath;
    private Uri uri;
    private File file;


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 12) {
                String headpicPaths = (String) msg.obj;
                if (headpicPaths != null) {

//                    headpicPaths是七牛云返回的地址    这里写自己的处理
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CODE_CAMERA:
                if (resultCode == RESULT_OK) {
                    upPath = file.getAbsolutePath();
                    break;
                }

            case REQUEST_CODE_ALBUM:
                if (resultCode == RESULT_OK) {
                    Uri uriAlbum = data.getData();
                    upPath = fromImageUriGetPath(uriAlbum);
                    break;
                }

            case REQUEST_CODE_VIDEO:
                if (resultCode == RESULT_OK) {
                    //从相册选取视频
                    Uri selectedVideo = data.getData();
                    upPath = fromVideoUriGetPath(selectedVideo);
                    break;
                }
                break;
        }
    }

    //    利用获取到的图片Uri  在获取到图片对应的path
    private String fromImageUriGetPath(Uri uri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        //picturePath就是图片在储存卡所在的位置
        String picturePath = cursor.getString(columnIndex);

        cursor.close();

        return picturePath;
    }

    //    利用获取到的视频Uri  在获取到视频对应的path
    private String fromVideoUriGetPath(Uri uri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri,
                new String[]{MediaStore.Video.Media.DATA}, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        //picturePath就是图片在储存卡所在的位置
        String picturePaths = cursor.getString(columnIndex);

        //这个videoThumb是获取该视频缩略图的地址    至于怎么获取的缩略图   我的博客里有    获取网络的  获取本地的 只需要视频地址就可以
        Bitmap netVideoBitmap = VideoFrameUtils.getLocalVideoBitmap(picturePaths);
        videoThumb = VideoFrameUtils.saveBitmap(UploadDynamicActivity.this, netVideoBitmap);
        
        cursor.close();

        return picturePaths;
    }

    //上传图片或视频到七牛云的方法
    private void uploadInfoToQiNiu(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String picSuffix = getPicSuffix(path);
                String randomNumCode = getRandomNumCode();
                // 设置图片名字
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String key = "icon_" + sdf.format(new Date()) + randomNumCode + "." + picSuffix;
                UploadManager uploadManager = new UploadManager();

                //这个getQNToken需要从后台获取 或者是自己从七牛云上找方法获取

                uploadManager.put(path, key, getQNToken, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if (info.isOK()) {
                            //这个是你将图片上传之后七牛云给你返回的地址    这个需要传给你们的后台
                            headpicPath = "http://qiniu.bjmocang.com/" + key;

                            Message message = handler.obtainMessage(12, headpicPath);
                            handler.sendMessage(message);
                        } else {
                            Log.e("tagxx", info.error);
                        }
                    }
                }, null);
            }
        }).start();

    }


    //调取相机
    private void fromCamera() {
        file = new File(Environment.getExternalStorageDirectory(), SystemClock.uptimeMillis() + ".jpg");
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.相机:
                fromCamera();
                break;
            case R.id.相册:
                Intent intentAlbum = new Intent(Intent.ACTION_PICK);
                intentAlbum.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intentAlbum, REQUEST_CODE_ALBUM);
                break;
            case R.id.视频:
                Intent intentVideo = new Intent(Intent.ACTION_PICK);
                intentVideo.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "video/*");
                startActivityForResult(intentVideo, REQUEST_CODE_VIDEO);
                break;
        }
    }

    @AfterPermissionGranted(1)//添加注解,是为了首次执行权限申请后,回调该方法
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            //已经申请过权限,直接调用相机
            // openCamera();
        } else {
            EasyPermissions.requestPermissions(this, "需要获取权限", 1, perms);
        }
    }

    //生成四位随机数
    public static String getRandomNumCode() {
        String codeNum = "";
        int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int next = random.nextInt(10000);
            codeNum += numbers[next % 10];
        }
        return codeNum;
    }

    /**
     * 获取图片后缀
     *
     * @param img_path 图片或者视频路径
     * @return
     */
    public static String getPicSuffix(String img_path) {
        if (img_path == null || img_path.indexOf(".") == -1) {
            return ""; //如果图片地址为null或者地址中没有"."就返回""
        }
        return img_path.substring(img_path.lastIndexOf(".") + 1).
                trim().toLowerCase();
    }

    //设置点击任意空白处隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View,一般情况下就是EditText(特殊情况就是轨迹求或者实体案件会移动焦点)
            View v = getCurrentFocus();
            if (HideInputUtil.isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 隐藏软键盘 
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}

5、补充一下,看很多小伙伴都说找不到这个工具类,在这里添加上。

public class VideoFrameUtils {
    public VideoFrameUtils() {
    }

    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();

        try {
            retriever.setDataSource(videoUrl, new HashMap());
            bitmap = retriever.getFrameAtTime(-1L);
        } catch (IllegalArgumentException var7) {
            var7.printStackTrace();
        } finally {
            retriever.release();
        }

        return bitmap;
    }

    public static Bitmap getLocalVideoBitmap(String localPath) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(localPath);
        Bitmap bitmap = media.getFrameAtTime(1L, 2);
        return bitmap;
    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(CompressFormat.JPEG, 100, baos);
        int options = 90;

        while(baos.toByteArray().length / 1024 > 800) {
            baos.reset();
            image.compress(CompressFormat.JPEG, options, baos);
            if (options > 10) {
                options -= 10;
            }
        }

        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, (Rect)null, (Options)null);
        return bitmap;
    }

    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath = context.getApplicationContext().getFilesDir().getAbsolutePath();

        File filePic;
        try {
            filePic = new File(savePath + "/image/map.jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException var5) {
            var5.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }
}

6、好了,到这里就结束了。希望能帮助到各位博友

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值