【问题标题】:Determine image size to reduce image size Android确定图像大小以减小图像大小 Android
【发布时间】:2018-10-17 10:00:45
【问题描述】:

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

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

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

【问题讨论】:

  • 您不会在代码中调整图像大小。您只需将其压缩为 75% 质量的 JPEG
  • 是的,问题是如何在保持纵横比的同时确定调整尺寸,这样我就不必分配随机值。
  • 这取决于您将如何使用该图像。
  • 我打算以任何屏幕的 3/4 大小显示此图像。为方便起见,让我们说不同设备的全屏尺寸,并且应该具有良好的质量。
  • 那么我的建议是将其缩小到 FullHD (1080x1920) 或类似以保持纵横比。它在 720x1280 或 1440x2560 屏幕上看起来都不错。作为一种算法,我建议使用这个:决定你要坚持哪一边(w或h)。假设 w(宽度)。目标宽度为 1080。现在计算目标高度,使用公式:targetHeight = targetWidth / actualWidth * actualHeight。现在您有了目标尺寸并且可以调整图像大小。

标签: android image-processing compression


【解决方案1】:

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

float aspectRatio = bmOptions.outWidth/bmOptions.outHeight;

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

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

【讨论】:

  • 感谢解答,但是如何确定480,同时保持质量但降低存储要求。
猜你喜欢
  • 2012-06-19
  • 2017-02-06
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
相关资源
最近更新 更多