工具類--文件,圖片的處理

1.  獲取本機圖片的路徑:

public static String handleImageOnKitKat(Context context, Intent data) {
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                String type = docId.split(":")[0];
                Uri contentUri = null;
                if (type.equalsIgnoreCase("image")) {
                    contentUri =  MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if (type.equalsIgnoreCase("audio")) {
                    contentUri =  MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else if (type.equalsIgnoreCase("video")) {
                    contentUri =  MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                }
                return getImagePath(context, contentUri, selection);
            } else if ("com.android.providers.media.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                return getImagePath(context, contentUri, null);
            } else if ("content".equals(uri.getAuthority())) {
                return getImagePath(context, uri, null);
            } else if ("file".equals(uri.getAuthority())) {
                return uri.getPath();
            }
        }
        return "";
    }

    private static String getImagePath(Context context, Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

2. 根據圖片路徑獲取Bitmap對象,並進行壓縮:

public static Bitmap getImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //開始讀入圖片,此時把options.inJustDecodeBounds 設回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此時返回bm爲空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //現在主流手機比較多是800*480分辨率,所以高和寬我們設置爲
        float hh = 800f;//這裏設置高度爲800f
        float ww = 480f;//這裏設置寬度爲480f
        //縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
        int be = 1;//be=1表示不縮放
        if (w > h && w > ww) {//如果寬度大的話根據寬度固定大小縮放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的話根據寬度固定大小縮放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//設置縮放比例
        Log.e(TAG,"inSampleSize="+be);
        //重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);//壓縮好比例大小後再進行質量壓縮
    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        int length = baos.toByteArray().length / 1024;
        Log.e(TAG,"length="+length);
        if (length>5000){
            //重置baos即清空baos
            baos.reset();
            //質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, 10, baos);
        }else if (length>4000){
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        }else if (length>3000){
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        }else if (length>2000){
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 70, baos);
        }

        Log.e(TAG,"baos.toByteArray().length="+baos.toByteArray().length);
        //循環判斷如果壓縮後圖片是否大於1M,大於繼續壓縮
        while (baos.toByteArray().length / 1024>1024) {
            //重置baos即清空baos
            baos.reset();
            //這裏壓縮options%,把壓縮後的數據存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            //每次都減少10
            options -= 10;
        }
        //把壓縮後的數據baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        //把ByteArrayInputStream數據生成圖片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

3.保存bitmap到本地 

public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath = Environment.getExternalStorageDirectory().toString() + "/nmpaapp/";
        File filePic;
        try {

            filePic = new File(savePath + System.currentTimeMillis() + ".jpg");
            Log.d("LUO", "圖片地址====" + filePic);
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            //不壓縮,保存本地
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }

4. 拍照後保存圖片並返回路徑:

public static String getCameraData(Intent data) {
        String path = null;
        Bitmap photo = null;
        if (data.getData() != null || data.getExtras() != null) { // 防止沒有返回結果
            Uri uri = data.getData();
            if (uri != null) {
                photo = BitmapFactory.decodeFile(uri.getPath()); // 拿到圖片
            }

            if (photo == null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    photo = (Bitmap) bundle.get("data");
                    String saveDir = Environment.getExternalStorageDirectory().toString() + "/nmpaapp/";
                    String filename = System.currentTimeMillis() + ".jpg";
                    File file = new File(saveDir, filename);
                    FileOutputStream fileOutputStream = null;
                    // 打開文件輸出流
                    try {
                        fileOutputStream = new FileOutputStream(file);
                        // 生成圖片文件
                        photo.compress(Bitmap.CompressFormat.JPEG,
                                100, fileOutputStream);
                        path = file.getPath();
                        Log.e("FileLoadUtils", "str=" + path);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return path;
    }

5. 獲取視頻文件的縮略圖

public static String getThumnailPath(String fromUser,String videoPath) {
        String fileName = "thvideo" + System.currentTimeMillis();
//        File file = new File(getMSNBasePath("5",fromUser), fileName);
        File file = createFileEm("5",fileName,fromUser);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
            ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

6. 保存文件:

public static void getFile(byte[] bfile, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            file = createFileEm("3",fileName,"");
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

7. 創建文件:

public static File createFile(String FileName) {
        String path = Environment.getExternalStorageDirectory().toString() + "/1nmpaapp";
        File file = new File(path);
        /**
         *如果文件夾不存在就創建
         */
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(path, FileName);
    }


    public static File createFileEm(String type,String FileName,String toUser) {
        String path = null;
        if (toUser != null && !toUser.equals("") ) {

            if (type.equals("3")) {
                path = BASE_PATH + toUser + "/voice/" ;
            } else if (type.equals("4")) {
                path =  BASE_PATH + toUser  + "/video/";
            }else if (type.equals("6")) {
                path = BASE_PATH + toUser  + "/file/";
            } else {
                path = BASE_PATH + toUser  + "/image/";
            }
        } else {
            if (type.equals("3")) {
                path = PathUtil.getInstance().getVoicePath() + "/" ;
            } else if (type.equals("4")) {
                path = PathUtil.getInstance().getVideoPath() + "/";
            }else if (type.equals("6")) {
                path = PathUtil.getInstance().getFilePath() + "/";
            } else {
                path = PathUtil.getInstance().getImagePath() + "/";
            }
        }

        File file = new File(path);
        /**
         *如果文件夾不存在就創建
         */
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(path, FileName);
    }

8. 採樣率壓縮(設置圖片的採樣率,降低圖片像素)

public static void samplingRateCompress(String filePath, File file) {
        // 數值越高,圖片像素越低
        int inSampleSize = 8;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
//          options.inJustDecodeBounds = true;//爲true的時候不會真正加載圖片,而是得到圖片的寬高信息。
        //採樣率
        options.inSampleSize = inSampleSize;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把壓縮後的數據存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        try {
            if (file.exists()) {
                file.delete();
            } else {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

9. 將字節數轉換爲對應單位的大小

public static float formatFileSize(long size, int unit) {
        if (size < 0) {
            return -1;
        }
        switch (unit) {
            case ConstUtils.KB:
                return size / ConstUtils.KB;
            case ConstUtils.MB:
                return size / ConstUtils.MB;
            case ConstUtils.GB:
                return size / ConstUtils.GB;
            default:
                return size / ConstUtils.MB;
        }
    }

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章