美文网首页
Android 图片保存压缩uri,bitmap,file互转(

Android 图片保存压缩uri,bitmap,file互转(

作者: wenju | 来源:发表于2022-06-29 20:56 被阅读0次
    import android.content.ContentResolver;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.ImageDecoder;
    import android.graphics.Matrix;
    import android.graphics.Paint;
    import android.media.ExifInterface;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    import android.text.TextUtils;
    import android.text.format.DateFormat;
    import android.util.Log;
    
    import androidx.annotation.Nullable;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class BitmapUtil {
    
        private BitmapUtil() {
            throw new UnsupportedOperationException("u can't instantiate me...");
        }
    
        static Bitmap getScaledBitmap(Context context, Uri imageUri, float maxWidth, float maxHeight, Bitmap.Config bitmapConfig) {
            String filePath = FileUtil.getRealPathFromURI(context, imageUri);
            Bitmap scaledBitmap = null;
    
            BitmapFactory.Options options = new BitmapFactory.Options();
    
            //by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
            //you try the use the bitmap here, you will get null.
            options.inJustDecodeBounds = true;
            Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
            if (bmp == null) {
                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(filePath);
                    BitmapFactory.decodeStream(inputStream, null, options);
                    inputStream.close();
                } catch (FileNotFoundException exception) {
                    exception.printStackTrace();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
    
            int actualHeight = options.outHeight;
            int actualWidth = options.outWidth;
    
            if (actualHeight == -1 || actualWidth == -1){
                try {
                    ExifInterface exifInterface = new ExifInterface(filePath);
                    actualHeight = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的高度
                    actualWidth = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的宽度
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            if (actualWidth <= 0 || actualHeight <= 0) {
                Bitmap bitmap2 = BitmapFactory.decodeFile(filePath);
                if (bitmap2 != null){
                    actualWidth = bitmap2.getWidth();
                    actualHeight = bitmap2.getHeight();
                }else{
                    return null;
                }
            }
    
            float imgRatio = (float) actualWidth / actualHeight;
            float maxRatio = maxWidth / maxHeight;
    
            //width and height values are set maintaining the aspect ratio of the image
            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;
                }
            }
    
            //setting inSampleSize value allows to load a scaled down version of the original image
            options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
    
            //inJustDecodeBounds set to false to load the actual bitmap
            options.inJustDecodeBounds = false;
    
            //this options allow android to claim the bitmap memory if it runs low on memory
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inTempStorage = new byte[16 * 1024];
    
            try {
                // load the bitmap getTempFile its path
                bmp = BitmapFactory.decodeFile(filePath, options);
                if (bmp == null) {
                    InputStream inputStream = null;
                    try {
                        inputStream = new FileInputStream(filePath);
                        BitmapFactory.decodeStream(inputStream, null, options);
                        inputStream.close();
                    } catch (IOException exception) {
                        exception.printStackTrace();
                    }
                }
            } catch (OutOfMemoryError exception) {
                exception.printStackTrace();
            }
            if (actualHeight <= 0 || actualWidth <= 0){
                return null;
            }
    
            try {
                scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, bitmapConfig);
            } catch (OutOfMemoryError exception) {
                exception.printStackTrace();
            }
    
            float ratioX = actualWidth / (float) options.outWidth;
            float ratioY = actualHeight / (float) options.outHeight;
    
            Matrix scaleMatrix = new Matrix();
            scaleMatrix.setScale(ratioX, ratioY, 0, 0);
    
            Canvas canvas = new Canvas(scaledBitmap);
            canvas.setMatrix(scaleMatrix);
            canvas.drawBitmap(bmp, 0, 0, new Paint(Paint.FILTER_BITMAP_FLAG));
    
            // 采用 ExitInterface 设置图片旋转方向
            ExifInterface exif;
            try {
                exif = new ExifInterface(filePath);
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
                Matrix matrix = new Matrix();
                if (orientation == 6) {
                    matrix.postRotate(90);
                } else if (orientation == 3) {
                    matrix.postRotate(180);
                } else if (orientation == 8) {
                    matrix.postRotate(270);
                }
                scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                        scaledBitmap.getWidth(), scaledBitmap.getHeight(),
                        matrix, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return scaledBitmap;
        }
    
        static File compressImage(Context context, Uri imageUri, float maxWidth, float maxHeight,
                                  Bitmap.CompressFormat compressFormat, Bitmap.Config bitmapConfig,
                                  int quality, String parentPath, String prefix, String fileName) {
            FileOutputStream out = null;
            String filename = generateFilePath(context, parentPath, imageUri, compressFormat.name().toLowerCase(), prefix, fileName);
            try {
                out = new FileOutputStream(filename);
                // 通过文件名写入
                Bitmap newBmp = BitmapUtil.getScaledBitmap(context, imageUri, maxWidth, maxHeight, bitmapConfig);
                if (newBmp != null){
                    newBmp.compress(compressFormat, quality, out);
                }
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ignored) {
                }
            }
    
            return new File(filename);
        }
    
        private static String generateFilePath(Context context, String parentPath, Uri uri,
                                               String extension, String prefix, String fileName) {
            File file = new File(parentPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            /** if prefix is null, set prefix "" */
            prefix = TextUtils.isEmpty(prefix) ? "" : prefix;
            /** reset fileName by prefix and custom file name */
            fileName = TextUtils.isEmpty(fileName) ? prefix + FileUtil.splitFileName(FileUtil.getFileName(context, uri))[0] : fileName;
            return file.getAbsolutePath() + File.separator + fileName + "." + extension;
        }
    
    
        /**
         * 计算inSampleSize
         */
        private 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;
        }
    
        public static File getFileSavedBitmap(Bitmap bitmap,Context context){
    
            if (bitmap == null || context == null ) {
                return null;
            }
            File temFileDir = getDiskCacheDir(context);//存储目录 缓存目录
    //        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File file = new File(temFileDir, getFileName());//将要保存图片的路径
    //        File file = new File(directory, getFileName());//将要保存图片的路径
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return file;
        }
    
        /**
         * 获取缓存目录 一般存放临时缓存数据
         * getCacheDir:/data/data/<application package>/cache目录(手机内存中)
         * getExternalCacheDir:用于获取SDCard/Android/data/你的应用包名/cache/目录
         */
        public static File getDiskCacheDir(Context context) {
            File cachePath;
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable()) {
                cachePath = context.getExternalCacheDir();
            } else {
                cachePath = context.getCacheDir();
            }
            return cachePath;
        }
    
    
        private static String getFileName() {
            long currentTimeMillis = System.currentTimeMillis();
            CharSequence format = DateFormat.format("yyyyMMdd_hhmmss", currentTimeMillis);
            String value = String.valueOf(currentTimeMillis);
            String name = format + "_" + value.substring(value.length() - 4, value.length());
            return name + ".png";
        }
    
        /**
         * 从文件读取Bitmap
         *
         * @param dst                目标路径
         * @param processOrientation 是否处理图片旋转角度
         * @return
         */
        public static Bitmap getBitmapFromFile(File dst, boolean processOrientation) {
            if (null != dst && dst.exists()) {
                try {
                    Bitmap bitmap = BitmapFactory.decodeFile(dst.getPath());
                    if (!processOrientation) {
                        return bitmap;
                    }
                    int orientation = getOrientation(dst.getPath());
                    if (orientation == 0) {
                        return bitmap;
                    } else {
                        Matrix matrix = new Matrix();
                        matrix.postRotate(orientation);
                        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                    }
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * 获取图片旋转角度
         *
         * @param path 根据路径
         */
        public static int getOrientation(final String path) {
            int rotation = 0;
            try {
                File file = new File(path);
                ExifInterface exif = new ExifInterface(file.getAbsolutePath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        rotation = 90;
                        break;
    
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        rotation = 180;
                        break;
    
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        rotation = 270;
                        break;
    
                    default:
                        rotation = 0;
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return rotation;
        }
    
        /**
         * 获取到的是真实的bitmap,如果能旋转就旋转
         * @param resolver
         * @param uri
         * @return 返回旋转后的照片
         */
        @Nullable
        public static Bitmap decodeImage(ContentResolver resolver, Uri uri) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    /**
                     * 注意!!!
                     * 通过此方法得到的bitmap无法使用getPixel()方法
                     * java.lang.IllegalStateException: unable to getPixel(), pixel access is not supported on Config#HARDWARE bitmaps
                     * 默认返回的是硬件HARDWARE内存中的bitmap,速度快,高效,但是无法使用getPixel()方法
                     */
                    return ImageDecoder.decodeBitmap(ImageDecoder.createSource(resolver, uri));
                } else {
                    return decodeImageLegacy(resolver, uri);
                }
    
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 获取真实的bitmap,返回的是处理过rotate的bitmap
         * @param resolver
         * @param uri
         * @return
         */
        @Nullable
        private static Bitmap decodeImageLegacy(ContentResolver resolver, Uri uri) {
            Bitmap bitmap = null;
            InputStream inputStream = null;
            try {
                inputStream = resolver.openInputStream(uri);
                bitmap = BitmapFactory.decodeStream(inputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap == null) {
                return null;
            }
    
            inputStream = null;
            int orientation = androidx.exifinterface.media.ExifInterface.ORIENTATION_NORMAL;
            try {
                inputStream = resolver.openInputStream(uri);
                if (inputStream != null) {
                    androidx.exifinterface.media.ExifInterface exifInterface = new androidx.exifinterface.media.ExifInterface(inputStream);
                    orientation = exifInterface.getAttributeInt(androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, androidx.exifinterface.media.ExifInterface.ORIENTATION_NORMAL);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            Log.d("EXIF", "Exif: " + orientation);
            if (orientation == androidx.exifinterface.media.ExifInterface.ORIENTATION_NORMAL) {
                return bitmap;
            } else {
                Matrix matrix = new Matrix();
                if (orientation == androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_90) {
                    matrix.postRotate(90);
                } else if (orientation == androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_180) {
                    matrix.postRotate(180);
                } else if (orientation == androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_270) {
                    matrix.postRotate(270);
                }
                return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            }
        }
    
    }
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.database.Cursor;
    import android.net.Uri;
    import android.provider.MediaStore;
    import android.provider.OpenableColumns;
    import android.text.TextUtils;
    import android.util.Log;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.text.DecimalFormat;
    
    public class FileUtil {
        static final String FILES_PATH = "CompressHelper";
        private static final int EOF = -1;
        private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    
        private FileUtil() {
            throw new UnsupportedOperationException("u can't instantiate me...");
        }
    
        /**
         * 根据文件路径获取文件
         *
         * @param filePath 文件路径
         * @return 文件
         */
        public static File getFileByPath(String filePath) {
            return TextUtils.isEmpty(filePath) ? null : new File(filePath);
        }
    
        /**
         * 判断文件是否存在
         *
         * @param filePath 文件路径
         * @return {@code true}: 存在<br>{@code false}: 不存在
         */
        public static boolean isFileExists(String filePath) {
            return isFileExists(getFileByPath(filePath));
        }
    
        /**
         * 判断文件是否存在
         *
         * @param file 文件
         * @return {@code true}: 存在<br>{@code false}: 不存在
         */
        public static boolean isFileExists(File file) {
            return file != null && file.exists();
        }
    
    
        /**
         * 重命名文件
         *
         * @param filePath 文件路径
         * @param newName  新名称
         * @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
         */
        public static boolean rename(String filePath, String newName) {
            return rename(getFileByPath(filePath), newName);
        }
    
        /**
         * 重命名文件
         *
         * @param file    文件
         * @param newName 新名称
         * @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
         */
        public static boolean rename(File file, String newName) {
            // 文件为空返回false
            if (file == null) return false;
            // 文件不存在返回false
            if (!file.exists()) return false;
            // 新的文件名为空返回false
            if (TextUtils.isEmpty(newName)) return false;
            // 如果文件名没有改变返回true
            if (newName.equals(file.getName())) return true;
            File newFile = new File(file.getParent() + File.separator + newName);
            // 如果重命名的文件已存在返回false
            return !newFile.exists()
                    && file.renameTo(newFile);
        }
    
        /**
         * 判断是否是目录
         *
         * @param dirPath 目录路径
         * @return {@code true}: 是<br>{@code false}: 否
         */
        public static boolean isDir(String dirPath) {
            return isDir(getFileByPath(dirPath));
        }
    
        /**
         * 判断是否是目录
         *
         * @param file 文件
         * @return {@code true}: 是<br>{@code false}: 否
         */
        public static boolean isDir(File file) {
            return isFileExists(file) && file.isDirectory();
        }
    
        /**
         * 判断是否是文件
         *
         * @param filePath 文件路径
         * @return {@code true}: 是<br>{@code false}: 否
         */
        public static boolean isFile(String filePath) {
            return isFile(getFileByPath(filePath));
        }
    
        /**
         * 判断是否是文件
         *
         * @param file 文件
         * @return {@code true}: 是<br>{@code false}: 否
         */
        public static boolean isFile(File file) {
            return isFileExists(file) && file.isFile();
        }
    
    
        /**
         * 重命名文件
         * @param file      文件
         * @param newName   新名字
         * @return          新文件
         */
        public static File renameFile(File file, String newName) {
            File newFile = new File(file.getParent(), newName);
            if (!newFile.equals(file)) {
                if (newFile.exists()) {
                    if (newFile.delete()) {
                        Log.d("FileUtil", "Delete old " + newName + " file");
                    }
                }
                if (file.renameTo(newFile)) {
                    Log.d("FileUtil", "Rename file to " + newName);
                }
            }
            return newFile;
        }
    
    
        /**
         * 获取临时文件
         * @param context   上下文
         * @param uri       url
         * @return          临时文件
         * @throws IOException
         */
        public static File getTempFile(Context context, Uri uri) throws IOException {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            String fileName = getFileName(context, uri);
            String[] splitName = splitFileName(fileName);
            File tempFile = File.createTempFile(splitName[0], splitName[1]);
            tempFile = renameFile(tempFile, fileName);
            tempFile.deleteOnExit();
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(tempFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (inputStream != null) {
                copy(inputStream, out);
                inputStream.close();
            }
    
            if (out != null) {
                out.close();
            }
            return tempFile;
        }
    
        /**
         * 截取文件名称
         * @param fileName  文件名称
         */
        static String[] splitFileName(String fileName) {
            String name = fileName;
            String extension = "";
            int i = fileName.lastIndexOf(".");
            if (i != -1) {
                name = fileName.substring(0, i);
                extension = fileName.substring(i);
            }
    
            return new String[]{name, extension};
        }
    
        /**
         * 获取文件名称
         * @param context   上下文
         * @param uri       uri
         * @return          文件名称
         */
        @SuppressLint("Range")
        static String getFileName(Context context, Uri uri) {
            String result = null;
            if (uri.getScheme().equals("content")) {
                Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
                try {
                    if (cursor != null && cursor.moveToFirst()) {
                        result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
            if (result == null) {
                result = uri.getPath();
                int cut = result.lastIndexOf(File.separator);
                if (cut != -1) {
                    result = result.substring(cut + 1);
                }
            }
            return result;
        }
    
        /**
         * 获取真实的路径
         * @param context   上下文
         * @param uri       uri
         * @return          文件路径
         */
        static String getRealPathFromURI(Context context, Uri uri) {
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor == null) {
                return uri.getPath();
            } else {
                cursor.moveToFirst();
                int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                String realPath = cursor.getString(index);
                cursor.close();
                return realPath;
            }
        }
    
    
        static int copy(InputStream input, OutputStream output) throws IOException {
            long count = copyLarge(input, output);
            if (count > Integer.MAX_VALUE) {
                return -1;
            }
            return (int) count;
        }
    
        static long copyLarge(InputStream input, OutputStream output)
                throws IOException {
            return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);
        }
    
        static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
                throws IOException {
            long count = 0;
            int n;
            while (EOF != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
                count += n;
            }
            return count;
        }
    
        public static String getReadableFileSize(long size) {
            if (size <= 0) {
                return "0";
            }
            final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
            int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
            return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
        }
    }
    
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.provider.MediaStore;
    import android.util.Log;
    
    import java.io.ByteArrayOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class ImageCompressionUtils {
        /**
         * 得到byte[]
         * LeanCloud上传文件是需要byte[]数组的
         * 这里对传入的图片Uri压缩,并转换为byte[]后返回
         *
         * @param activity 上下文
         * @param uri      传入图片的Uri
         * @return byte[]
         */
        public static byte[] getCompressionImageByte(Activity activity, Uri uri) throws IOException {
            //先进行尺寸压缩
    //        Bitmap bitmap = getCompressionBitmapFormUri(activity, uri);
            Bitmap bitmap = BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(uri));
            //再进行质量压缩
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);//100表示不压缩,直接放到out里面
            int options = 90;//压缩比例
            while (out.toByteArray().length / 1024 > 800) { // 循环判断如果压缩后图片是否大于800kb,大于继续压缩
                out.reset(); // 重置baos即清空baos
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, out);// 这里压缩options%,把压缩后的数据存放到baos中
                options -= 10;// 每次都减少10
            }
            Log.e("压缩-提交", out.toByteArray().length + "");
    
            byte[] bs = out.toByteArray();//转换为byte提交
    
            return bs;
        }
    
        public static byte[] getCompressionImageByte(Bitmap bitmap) throws IOException {
            //再进行质量压缩
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);//100表示不压缩,直接放到out里面
            int options = 90;//压缩比例
            while (out.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                out.reset(); // 重置baos即清空baos
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, out);// 这里压缩options%,把压缩后的数据存放到baos中
                options -= 10;// 每次都减少10
            }
            Log.e("压缩-提交", out.toByteArray().length + "");
    
            byte[] bs = out.toByteArray();//转换为byte提交
    
            return bs;
        }
    
    
        /**
         * 得到bitmap
         * @param activity 上下文
         * @param uri      传入图片的Uri
         * @return byte[]
         */
        public static Bitmap getCompressionImageBitmap(Activity activity, Uri uri) throws IOException {
            return byteToBitmap(getCompressionImageByte(activity,uri));
        }
    
        public static Bitmap getCompressionImageBitmap(Bitmap bitmap) throws IOException {
            return byteToBitmap(getCompressionImageByte(bitmap));
        }
    
        /**
         * 得到压缩后的图片uri
         * @param activity 上下文
         * @param uri      传入图片的Uri,或者bitmap
         * @return byte[]
         */
        public static Uri getCompressionImageUri(Activity activity, Uri uri) throws IOException {
            return bitmapToUri(activity,byteToBitmap(getCompressionImageByte(activity,uri)));
        }
    
        public static Uri getCompressionImageUri(Activity activity, Bitmap bitmap) throws IOException {
            return bitmapToUri(activity,byteToBitmap(getCompressionImageByte(bitmap)));
        }
    
    
        /**
         * 图片尺寸压缩
         *
         * 宽度高度不一样:依靠规定的高或宽其一最大值来做界限
         * 高度宽度一样:依照规定的宽度压缩
         *
         * @param uri
         */
        public static Bitmap getCompressionBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
            InputStream input = ac.getContentResolver().openInputStream(uri);
            BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
            onlyBoundsOptions.inJustDecodeBounds = true;
            onlyBoundsOptions.inDither = true;//optional
            onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
            BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
            input.close();
            int originalWidth = onlyBoundsOptions.outWidth;
            int originalHeight = onlyBoundsOptions.outHeight;
            if ((originalWidth == -1) || (originalHeight == -1))
                return null;
            //图片分辨率以750x450为标准
            float hh = 750f;//这里设置高度为750f
            float ww = 450f;//这里设置宽度为450f
            float sq = 300f;//这里设置正方形为300f
            //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
            Log.e("缩放", originalWidth + "..." + originalHeight);
            int be = 1;//be=1表示不缩放
            if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大,根据宽度固定大小缩放
                be = (int) (originalWidth / ww);
            } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高,根据宽度固定大小缩放
                be = (int) (originalHeight / hh);
            } else if (originalWidth == originalHeight && originalWidth > sq) {//如果高度和宽度一样,根据任意一边大小缩放
                //be = (int) (originalHeight / sq);
                be = (int) (originalWidth / sq);
            }
            if (be <= 0) {//如果缩放比比1小,那么保持原图不缩放
                be = 1;
            }
            Log.e("缩放", be + "");
            //比例压缩
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmapOptions.inSampleSize = be;//设置缩放比例
            bitmapOptions.inDither = true;//optional
            bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
            input = ac.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
            input.close();
    
            return bitmap;//再进行质量压缩
        }
    
        public static Bitmap byteToBitmap(byte[] bs){
            return BitmapFactory.decodeByteArray(bs, 0, bs.length);
        }
    
        public static Uri bitmapToUri(Context context, Bitmap bitmap){
            return Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "ok",null));
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Android 图片保存压缩uri,bitmap,file互转(

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