Android 图片压缩 相机相册获取照片 高质量压缩 不会失真

2018-07-11  本文已影响0人  nade_s

先说一下 为什么进行图片压缩 主要有两个方面的原因 一是为了优化交互  减少上传图片的等待时间 和响应时间 而是为了减少服务器和数据库压力 减少图片的储存占用空间 当然使用第三方存储的可以忽略 例如七牛 当然我们也是能省则省嘛

本人今天整理一下android 关于照片压缩问题 关于图片压缩好很多方式 例如说质量压缩 比例压缩 等等 

今天笔者阐述的是比例压缩与质量压缩相结合的方式 压缩效果是很明显的 并且压缩后的图片不会失真模糊 

关于权限问题以及7.0 file路径问题 demo 已经做好适配 这里就不过多的阐述了 下载demo 解压直接查看就好了 

下面就直接上代码 

xml 文件

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:orientation="vertical">

android:id="@+id

_camere"

android:layout_width="200dp"

android:layout_height="50dp"

android:text="CAMARE" />

android:id="@+id

_gallery"

android:layout_width="200dp"

android:layout_height="50dp"

android:layout_marginTop="10dp"

android:text="GALLERY" />

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" />

// 相机

    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);    }

uri 转 StringFilePath

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;

        }

    }

// file 工具 

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;

        }

    }

压缩工具

public classBitmapUtils{ 

 // 计算比例 

 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);

            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        }

        return inSampleSize;

    }

    /**    * 根据路径获得到图片并压缩返回bitmap用于显示    *    * @paramfilePath    * @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;

    }

    /**    * 质量压缩   

 * @parambmp bitmap 对象    

 * @paramfile 路径文件   

 */    

        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();

        }

    }

}

本文是采用 比例压缩 和 质量压缩 结合的方法进行图片压缩  压缩后 图片质量很好 不会有失真的情况

看一下效果

压缩比例

压缩后

压缩后

好了 到这里就结束了 欢迎私信和留言  demo 下载

上一篇下一篇

猜你喜欢

热点阅读