Android 关于图片压缩

作者: 凤舞梦想 | 来源:发表于2015-12-15 16:16 被阅读734次

最近在做一个图片上传的功能,发现上传的图片经常超过2M,而且还会造成OutOfMemoryError。同时拍照的相片会出现纵向或者横向,需要进行旋转。需要进行对图片进行压缩,同时需要进行压缩比例,防止造成图片失真。

    public String compressImage(String imageUri) {
            String filePath = getRealPathFromURI(imageUri);
            Bitmap scaledBitmap = null;
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 设为true的话,在decode时将会返回null,通过此设置可以去查询一个bitmap的属性,比如bitmap的长与宽,而不占用内存大小
            options.inJustDecodeBounds = true;
            Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

            int actualHeight = options.outHeight;
            int actualWidth = options.outWidth;
         
            float maxHeight = 816.0f;
            float maxWidth = 612.0f;
            float imgRatio = actualWidth / actualHeight;
            float maxRatio = maxWidth / maxHeight;

            // width and height 设置为bitmap宽高比
            if (actualHeight > maxHeight || actualWidth > maxWidth) {
                if (imgRatio < maxRatio) {
                    imgRatio = maxHeight / actualHeight;
                    actualWidth = (int) (imgRatio * actualWidth);
                    actualHeight = (int) maxHeight;
                } else if (imgRatio > maxRatio) {
                    imgRatio = maxWidth / actualWidth;
                    actualHeight = (int) (imgRatio * actualHeight);
                    actualWidth = (int) maxWidth;
                } else {
                    actualHeight = (int) maxHeight;
                    actualWidth = (int) maxWidth;

               }
            }

            // 获取图像压缩比
            options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

            options.inJustDecodeBounds = false;

            // 当存储Pixel的内存空间在系统内存不足时可以被回收, 
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inTempStorage = new byte[16 * 1024];

            try {
                // load the bitmap 
                bmp = BitmapFactory.decodeFile(filePath, options);
            } catch (OutOfMemoryError exception) {
                exception.printStackTrace();
    
            }
            try {
                scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
            } catch (OutOfMemoryError exception) {
                exception.printStackTrace();
            }

            float ratioX = actualWidth / (float) options.outWidth;
            float ratioY = actualHeight / (float) options.outHeight;
            float middleX = actualWidth / 2.0f;
            float middleY = actualHeight / 2.0f;

            Matrix scaleMatrix = new Matrix();
            scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

            Canvas canvas = new Canvas(scaledBitmap);
            canvas.setMatrix(scaleMatrix);
            canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2,
                    new Paint(Paint.FILTER_BITMAP_FLAG));

            // 检查图像是否旋转 
            ExifInterface exif;
            try {
                exif = new ExifInterface(filePath);

                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
                Log.d("EXIF", "Exif: " + orientation);
                Matrix matrix = new Matrix();
                if (orientation == 6) {
                    matrix.postRotate(90);
                    Log.d("EXIF", "Exif: " + orientation);
                } else if (orientation == 3) {
                    matrix.postRotate(180);
                    Log.d("EXIF", "Exif: " + orientation);
                } else if (orientation == 8) {
                    matrix.postRotate(270);
                    Log.d("EXIF", "Exif: " + orientation);
                }
                scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(),
                        matrix, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileOutputStream out = null;
            String filename = getFilename();
            try {
                out = new FileOutputStream(filename);
                // write the compressed bitmap at the destination specified by filename.
                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            return filename;
        }

getFilename :: 在SD卡用于存储图像地址:

public String getFilename() {
    File file = new File(Environment.getExternalStorageDirectory().getPath(), "Folder/Images");
    if (!file.exists()) {
        file.mkdirs();
    }
    String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
    return uriSting;
}

calculateInSampleSize :: 计算inSampleSize的值:

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;
    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }
    return inSampleSize;
}

相关文章

  • Android 关于图片压缩

    最近在做一个图片上传的功能,发现上传的图片经常超过2M,而且还会造成OutOfMemoryError。同时拍照的相...

  • 我们常用的图片格式到底有什么区别?

    今天在整理图片工具类的时候,翻看了一下Android关于图片部分压缩格式的源码。里面枚举了3种图片压缩格式:JPE...

  • 图片压缩

    Android应用开发中三种常见的图片压缩方法,分别是:质量压缩法、比例压缩法(根据路径获取图片并压缩)和比例压缩...

  • Android:图片压缩的几种方式

    1、前言 在Android中,图片的压缩对于内存的优化很重要 通过这篇文章对Android中的几种图片压缩方式进行...

  • Android自动化批量图片压缩插件McImage

    文 | Promise Sun 一、资源图片压缩 关于资源图片压缩,可以在tinypng这个网站进行手动图片压缩,...

  • 图片压缩

    Android图片压缩常用的有质量压缩、尺寸压缩、采样率压缩以及通过JNI调用libjpeg库来进行压缩(尺寸压缩...

  • 【Android开发基础系列】图片专题

    1 图片编辑处理 1.1 图片裁切 转载自:bitmap的六种压缩方式,Android图片压缩 http://bl...

  • 资源图片优化

    tinypng 在线图片压缩 webP android studio选中图片右键Convert to webP

  • Android

    Android常用图片压缩方式 质量压缩 尺寸压缩 1. 质量压缩 质量压缩通过相应算法进行优化Bitmap的位深...

  • bitmap的六种压缩方式,Android图片压缩

    此处分享一个图片的压缩处理方式 : bitmap的六种压缩方式,Android图片压缩 转载链接,点击查看详情 !

网友评论

    本文标题:Android 关于图片压缩

    本文链接:https://www.haomeiwen.com/subject/msvuhttx.html