Android 相机相册获取照片 高质量压缩 不会失真模糊 含demo

本人今天整理一下android 关于照片压缩问题 关于图片压缩好很多方式 例如说质量压缩 比例压缩 等等
今天笔者阐述的是比例压缩与质量压缩相结合的方式 压缩效果是很明显的 并且压缩后的图片不会失真模糊
关于权限问题以及7.0 file路径问题 demo 已经做好适配 这里就不过多的阐述了 下载demo 解压直接查看就好了
下面就直接上代码
xml 文件

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <Button
            android:id="@+id/bt_camere"
            android:layout_width="200dp"
            android:layout_height="50dp"
            android:text="CAMARE" />

        <Button
            android:id="@+id/bt_gallery"
            android:layout_width="200dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:text="GALLERY" />

        <ImageView
            android:id="@+id/im_src"
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_marginTop="20dp"
            android:rotation="-10"
            android:src="@mipmap/ic_launcher" />

    </LinearLayout>
    // 相机
    private void takeGallery() {
        out = new File(FileUtils.getFileName());
        if (Build.VERSION.SDK_INT >= 24){
            outputFileUri = FileProvider.getUriForFile(MainActivity.this,this.getPackageName()+".provider", out);
        }else {
            outputFileUri = Uri.fromFile(out);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, TYPE_CAMERE);
        }
    }

    // 相册
    private void takeCamere() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
        startActivityForResult(intent, TYPE_GALLERY);
    }
 private String getRealPathFromURI(Uri contentURI) {
        String result = null;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            result = contentURI.getPath();
        } else {
            if (cursor.moveToFirst()){
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                if (idx > -1){
                    result = cursor.getString(idx);
                }
                cursor.close();
            }
        }
        return result;
    }
//uri 获取 path
    private String getRealPathFromURI(Uri contentURI) {
        String result = null;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            result = contentURI.getPath();
        } else {
            if (cursor.moveToFirst()){
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                if (idx > -1){
                    result = cursor.getString(idx);
                }
                cursor.close();
            }
        }
        return result;
    }

// 回调

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode!=RESULT_OK)
            return;
        String fileName = FileUtils.getFileName();
        switch (requestCode){
            case TYPE_CAMERE:
                 Bitmap smallBitmap = BitmapUtils.getSmallBitmap(out.getAbsolutePath(), 480, 480,new File(fileName));
                img_src.setImageBitmap(smallBitmap);
                break;
            case TYPE_GALLERY:
                Bitmap smallBitmap1 = BitmapUtils.getSmallBitmap(getRealPathFromURI(data.getData()), 480, 480,new File(fileName));
                img_src.setImageBitmap(smallBitmap1);
                break;
        }

    }
// 文件工具
  public class FileUtils {
        // Create an image file name
        public static String getFileName(){
            String fileName  =null;
            long currentTimeMillis = System.currentTimeMillis();
            String pathName = Environment.getExternalStorageDirectory() + "/DCIM/";
            File file = new File(pathName);
            file.mkdirs();
            fileName = pathName + currentTimeMillis+".jpg";

            return fileName;

        }


    }

// bitmap 工具 压缩图片 设置宽高并根据宽高计算比例

/**
* 作者: Nade_S on 2018/2/28.
* 大图压缩
*/

public class BitmapUtils {

    // 计算比例
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
    /**
     * 根据路径获得到图片并压缩返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight,File imgPath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;  //只返回图片的大小信息
        BitmapFactory.decodeFile(filePath, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        Log.d("tag", "getSmallBitmap: 生成bitmap----"+filePath+"//"+bitmap);
        compressBmpToFile(bitmap,imgPath);
        return bitmap;
    }

    /**
     * 质量压缩
     * @param bmp bitmap 对象
     * @param file 路径文件
     */
    public static void compressBmpToFile(Bitmap bmp,File file){

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 100) {
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

压缩效果 上图看一下面是8.0的小米6测试效果

这里写图片描述
压缩前
这里写图片描述

压缩后

这里写图片描述

demo 下载—->>>> https://download.csdn.net/download/naide_s/10331414

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值