Android之图片压缩和Uri与String类型的路径转换,获取图片,文件大小的工具类

转自:http://www.jianshu.com/p/ad2d020ef017?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=qq

图片压缩和路径转换,获取图片,文件大小的工具类:

  • 知道图片路径 Uri 转换为 String 路径
  • 对图片进行压缩并且命名存储到指定的路径targetPath
  • 根据路径获得图片信息并按比例压缩,返回bitmap
  • 调用此方法自动计算指定文件或指定文件夹的大小
  • 获取指定文件大小
  • 转换文件大小
  • 旋转照片
  • 将图片路径Uri所表示的图片转换成指定大小的照片显示出来
  • 获取bitmap的大小

    知道图片路径 Uri 转换为 String 路径

    /**
         * Try to return the absolute file path from the given Uri
         * @param context   知道图片路径 Uri 转换为 String 路径            TODO
         * @param uri
         * @return the file path or null
        *
        *Uri获取String类型的绝对路径
        *String path = Uri.getPath();
         */
        public static String getRealFilePath( final Context context, final Uri uri ) {
            if ( null == uri ) return null;
            final String scheme = uri.getScheme();
            String data = null;
            if ( scheme == null )
                data = uri.getPath();
            else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
                data = uri.getPath();
            } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
                Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
                if ( null != cursor ) {
                    if ( cursor.moveToFirst() ) {
                        int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                        if ( index > -1 ) {
                            data = cursor.getString( index );
                        }
                    }
                    cursor.close();
                }
            }
            return data;
        }

    对图片进行压缩并且命名存储到指定的路径targetPath

    /**
     * 对图片进行压缩命名存储到指定的路径path
     * @param filePath  原图片路径
     * @param targetPath  存储图片目标路径
     * @param quality  图片质量  1-100
     * @return
     */
    public static String compressImage(String filePath, String targetPath, int quality)  {
        Bitmap bm = getSmallBitmap(filePath);//获取一定尺寸的图片
        int degree = readPictureDegree(filePath);//获取相片拍摄角度
        if(degree!=0){//旋转照片角度,防止头像横着显示
            bm=rotateBitmap(bm,degree);
        }
        File outputFile=new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
            }else{
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
        }catch (Exception e){}
        return outputFile.getPath();
    }

    根据路径获得图片信息并按比例压缩,返回bitmap

    /**
     * 根据路径获得图片信息并按比例压缩,返回bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿,获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    调用此方法自动计算指定文件或指定文件夹的大小

    /**
         * 调用此方法自动计算指定文件或指定文件夹的大小
         * @param filePath 文件路径
         * @return 计算好的带B、KB、MB、GB的字符串
         */
        public static String getAutoFileOrFilesSize(String filePath){
            File file=new File(filePath);
            long blockSize=0;
            try {
                if(file.isDirectory()){
                    blockSize = getFileSize(file);
                }else{
                    blockSize = getFileSize(file);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("获取文件大小","获取失败!");
            }
            return FormetFileSize(blockSize);
        }

    获取指定文件大小

    /**
         * 获取指定文件大小
         * @param
         * @return
         * @throws Exception
         */
        private static long getFileSize(File file) throws Exception
        {
            long size = 0;
            if (file.exists()){
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            }
            else{
                file.createNewFile();
                Log.e("获取文件大小","文件不存在!");
            }
            return size;
        }

    转换文件大小

    /**
     * 转换文件大小
     * @param fileS
     * @return
     */
    private static String FormetFileSize(long fileS)
    {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize="0B";
        if(fileS==0){
            return wrongSize;
        }
        if (fileS < 1024){
            fileSizeString = df.format((double) fileS) + "B";
        }
        else if (fileS < 1048576){
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        }
        else if (fileS < 1073741824){
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        }
        else{
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    旋转照片

    /**
     * 旋转照片
     * @param bitmap
     * @param degress
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap,int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    将图片路径Uri所表示的图片转换成指定大小的照片显示出来

    /**
      * 将图片路径Uri所表示的图片转换成指定大小的照片显示出来
      */
    public static Bitmap getThumbnail(Context mContext, Uri uri, int reqWidth, int reqHeight) {
        Bitmap srcBmp = BitmapUtils.decodeSampledFromUri(mContext, uri, reqWidth, reqHeight);
        // If picture is smaller than required thumbnail
        Bitmap dstBmp;
        if (srcBmp.getWidth() < reqWidth && srcBmp.getHeight() < reqHeight) {
            dstBmp = ThumbnailUtils.extractThumbnail(srcBmp, reqWidth, reqHeight);
            // Otherwise the ratio between measures is calculated to fit requested thumbnail's one
        } else {
            int x = 0, y = 0, width = srcBmp.getWidth(), height = srcBmp.getHeight();
            float ratio = ((float) reqWidth / (float) reqHeight) * ((float) srcBmp.getHeight() / (float) srcBmp.getWidth());
            if (ratio < 1) {
                x = (int) (srcBmp.getWidth() - srcBmp.getWidth() * ratio) / 2;
                width = (int) (srcBmp.getWidth() * ratio);
            } else {
                y = (int) (srcBmp.getHeight() - srcBmp.getHeight() / ratio) / 2;
                height = (int) (srcBmp.getHeight() / ratio);
            }
            dstBmp = Bitmap.createBitmap(srcBmp, x, y, width, height);
        }
        return dstBmp;
    }

    获取bitmap的大小

    //获取bitmap的大小
    public static long getBitmapsize(Bitmap bitmap){
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        }
        // Pre HC-MR1
        return bitmap.getRowBytes() * bitmap.getHeight();
    
    }

    通过压缩图片的尺寸来压缩图片大小

    /**
     * 通过压缩图片的尺寸来压缩图片大小  TODO
     *
     * @param pathName     图片的完整路径
     * @param targetWidth  缩放的目标宽度
     * @param targetHeight 缩放的目标高度
     * @return 缩放后的图片
     */
    public static Bitmap compressBySize(String pathName, int targetWidth,
                                        int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片,只是获取图片的头部信息,包含宽高等;
        Bitmap bitmap1 = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度;
        int imgWidth = opts.outWidth;
        int imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数;
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后,加载图片进内容;
        opts.inJustDecodeBounds = false;
        bitmap1 = BitmapFactory.decodeFile(pathName, opts);
        return bitmap1;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值