如何将图像大小减小到1MB

Ays*_*raf 5 android image-resizing

我希望我的应用程序上传没有大小限制的图像,但是在代码中,如果图像大小超出限制,我想将图像大小调整为1MB。我已经尝试了许多方法,但是找不到上面提到的要求的任何代码。

我已经尝试过一次:

public void scaleDown() {
    int width = stdImageBmp.getWidth();
    int height = stdImageBmp.getHeight();
    Matrix matrix = new Matrix();
    float scaleWidth = ((float) MAX_WIDTH) / width;
    float scaleHeight = ((float) MAX_HEIGHT) / height;


    matrix.postScale(scaleWidth, scaleHeight);
    stdImageBmp = Bitmap.createBitmap(stdImageBmp, 0, 0, width, height, matrix, true);

    File Image = new File("path");


    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    //compress bmp
    stdImageBmp.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();


    imgViewStd.setImageBitmap(stdImageBmp);
    Log.d("resizedBitmap", stdImageBmp.toString());

    width = stdImageBmp.getWidth();
    height = stdImageBmp.getHeight();
    System.out.println("imgWidth" + width);
    System.out.println("imgHeight" + height);
}
Run Code Online (Sandbox Code Playgroud)

M.W*_*vez 5

您可以使用此代码调整位图的大小,并且图像大小<1MB,我建议使用 480x640

public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        return Bitmap.createBitmap(
                bm, 0, 0, width, height, matrix, false);
    }
Run Code Online (Sandbox Code Playgroud)

  • 当然。https://developer.android.com/training/displaying-bitmaps/index.html (2认同)