android 拍照上传

1、拍照时先传Uri


 /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getActivity().getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

2、拍完后 将原有Uri写入到沙盒里 最终转成File


 /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider. android 10
     */
    public static File uriToFileApiQ(Uri uri, Context context) {
        File file = null;
        if(uri == null) return file;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis()+ Math.round((Math.random() + 1) * 1000)
                    +"."+ MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));

//            注释掉的方法可以获取到原文件的文件名,但是比较耗时
//            Cursor cursor = contentResolver.query(uri, null, null, null, null);
//            if (cursor.moveToFirst()) {
//                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));}

            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                copyFile(is, fos);
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static void copyFile(InputStream is, FileOutputStream fos) {
        try{
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            System.out.println("File successfully copied.");
        } catch(IOException e){
            System.out.println("Handle the exception");
            e.printStackTrace();
        }
    }

7.0以下创建路径方法


public static File createTmpFile(Context context) throws IOException{
        File dir = null;
        if(TextUtils.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)) {
            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            if (!dir.exists()) {
                dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera");
                if (!dir.exists()) {
                    dir = getCacheDirectory(context, true);
                }
            }
        }else{
            dir = getCacheDirectory(context, true);
        }
        return File.createTempFile(JPEG_FILE_PREFIX, JPEG_FILE_SUFFIX, dir);
    }


    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

    /**
     * Returns application cache directory. Cache directory will be created on SD card
     * ("/Android/data/[app_package_name]/cache") if card is mounted and app has appropriate permission. Else -
     * Android defines cache directory on device's file system.
     *
     * @param context Application context
     * @return Cache {@link File directory}.
* NOTE: Can be null in some unpredictable cases (if SD card is unmounted and * {@link android.content.Context#getCacheDir() Context.getCacheDir()} returns null). */ public static File getCacheDirectory(Context context) { return getCacheDirectory(context, true); } /** * Returns application cache directory. Cache directory will be created on SD card * ("/Android/data/[app_package_name]/cache") (if card is mounted and app has appropriate permission) or * on device's file system depending incoming parameters. * * @param context Application context * @param preferExternal Whether prefer external location for cache * @return Cache {@link File directory}.
* NOTE: Can be null in some unpredictable cases (if SD card is unmounted and * {@link android.content.Context#getCacheDir() Context.getCacheDir()} returns null). */ public static File getCacheDirectory(Context context, boolean preferExternal) { File appCacheDir = null; String externalStorageState; try { externalStorageState = Environment.getExternalStorageState(); } catch (NullPointerException e) { // (sh)it happens (Issue #660) externalStorageState = ""; } catch (IncompatibleClassChangeError e) { // (sh)it happens too (Issue #989) externalStorageState = ""; } if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState) && hasExternalStoragePermission(context)) { appCacheDir = getExternalCacheDir(context); } if (appCacheDir == null) { appCacheDir = context.getCacheDir(); } if (appCacheDir == null) { String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/"; appCacheDir = new File(cacheDirPath); } return appCacheDir; } /** * Returns individual application cache directory (for only image caching from ImageLoader). Cache directory will be * created on SD card ("/Android/data/[app_package_name]/cache/uil-images") if card is mounted and app has * appropriate permission. Else - Android defines cache directory on device's file system. * * @param context Application context * @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images") * @return Cache {@link File directory} */ public static File getIndividualCacheDirectory(Context context, String cacheDir) { File appCacheDir = getCacheDirectory(context); File individualCacheDir = new File(appCacheDir, cacheDir); if (!individualCacheDir.exists()) { if (!individualCacheDir.mkdir()) { individualCacheDir = appCacheDir; } } return individualCacheDir; } private static File getExternalCacheDir(Context context) { File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data"); File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache"); if (!appCacheDir.exists()) { if (!appCacheDir.mkdirs()) { return null; } try { new File(appCacheDir, ".nomedia").createNewFile(); } catch (IOException e) { } } return appCacheDir; } private static boolean hasExternalStoragePermission(Context context) { int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION); return perm == PackageManager.PERMISSION_GRANTED; } //图片的Uri imageUri= Uri.fromFile(mTmpFile);

你可能感兴趣的:(android 拍照上传)