首页 > 解决方案 > 确定图像大小以减小图像大小 Android

问题描述

有没有减少图像(从手机摄像头拍摄)的存储容量。据我所知,可以更改的参数是图像的质量、编码和尺寸。为此,我正在使用 zetbaitsu/Compressor lib。

问题是如何确定云存储所需的尺寸,以便图像在各种 Android 屏幕尺寸/分辨率上具有良好的质量,同时显着降低存储需求。

File image = fileMessageContainer.getFile();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
int width = bmOptions.outWidth;
int height = bmOptions.outHeight;
Log.d("myApp", "uncompressed" +  width + " height: " +  height);

Bitmap bitmap = compressImages(image, width, height);
Log.d("myApp", "compressed" +  bitmap.getWidth() + " height: " +  
bitmap.getHeight());

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteArray = baos.toByteArray();

Log.d("myApp", "original data " + byteArray.length);

    private Bitmap compressImages(File actualImage, int width, int height){
        try {
         return new Compressor(context)
        .setQuality(75)
        .setMaxHeight(height)
        .setMaxWidth(width)
        .setCompressFormat(Bitmap.CompressFormat.JPEG)
        .compressToBitmap(actualImage);
        }catch (Exception e){
           Log.d("myApp", "compressImages-Error " + e.getMessage());
        }
        return null;
    }

    private byte[] convertToByteArray(Bitmap b){
        int bytes = b.getByteCount();

        ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
        b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

        return buffer.array(); //Get the underlying array containing the data.
    }

控制台输出

未压缩宽度:2448 高度:3264 压缩宽度:2448 高度:3264 原始数据31961088

标签: androidimage-processingcompression

解决方案


您需要声明纵横比,然后将其用于新的宽度和高度

float aspectRatio = bmOptions.outWidth/bmOptions.outHeight;

int width = 480; //Your choice
int height = Math.round(width / aspectRatio);

Bitmap bitmap = compressImages(image, width, height);

推荐阅读