确定图像尺寸以减小Android图像尺寸

时间:2018-10-17 10:00:45

标签: android image-processing compression

有没有地方要减少图像(从手机摄像头拍摄)的存储容量。据我所知,可以更改的参数是图像的质量,编码和尺寸。为此,我正在使用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

1 个答案:

答案 0 :(得分:0)

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

float aspectRatio = bmOptions.outWidth/bmOptions.outHeight;

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

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