如何调整图像大小以适应多个屏幕密度

时间:2012-12-01 13:00:15

标签: android android-image android-screen-support

我需要在网格项中添加头像。

我想知道如何处理从手机图库中选择的图像的大小调整。一旦被选中,我想会有一些调整大小,以适应网格。

但是,我是否需要为每个屏幕密度存储已调整大小的图像;存储一个xhdpi版本并缩小其他设备,或者以其他方式聪明?

原因是,应用程序将此图像存储到云数据库,其他人可以下载此图像。他们可能会在不同的设备上看到图像(因此需要不同的图像尺寸)。如何处理这张图片的管理?

4 个答案:

答案 0 :(得分:4)

  

做这样的事情:

 DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    Bitmap bitmapOrg = new BitmapDrawable(getResources(), new  ByteArrayInputStream(imageThumbnail)).getBitmap();

    int width = bitmapOrg.getWidth();
    int height = bitmapOrg.getHeight();

    float scaleWidth = metrics.scaledDensity;
    float scaleHeight = metrics.scaledDensity;

    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);

答案 1 :(得分:2)

我希望您能找到以下有用的代码。它将以最小的开销返回具有reqd维度的图像。我已经使用了很多次,像魅力一样。您可以根据目标设备设置所需的尺寸。缩放将导致图片模糊,但事实并非如此。

private Bitmap getBitmap(Uri uri) {                             
    InputStream in = null;
    try {
        final int IMAGE_MAX_SIZE = 200000; // 0.2MP
        in = my_context.getContentResolver().openInputStream(uri);

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;                    //request only the dimesion
        BitmapFactory.decodeStream(in, null, o);
        in.close();

        int scale = 1;
        while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
            scale++;
        }

        Bitmap b = null;
        in = my_context.getContentResolver().openInputStream(uri);
        if (scale > 1) {
            scale--;
            // scale to max possible inSampleSize that still yields an image
            // larger than target
            o = new BitmapFactory.Options();
            o.inSampleSize = scale;
            b = BitmapFactory.decodeStream(in, null, o);
            // resize to desired dimensions
            int height = b.getHeight();
            int width = b.getWidth();

            double y = Math.sqrt(IMAGE_MAX_SIZE
                    / (((double) width) / height));
            double x = (y / height) * width;

            Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, (int) y, true);
            b.recycle();
            b = scaledBitmap;
            System.gc();
        } else {
            b = BitmapFactory.decodeStream(in);
        }
        in.close();

        return b;
    } catch (IOException e) {

        return null;
    }

}

答案 2 :(得分:1)

android:scaleType="fitXY"
android:layout_gravity="center"

将缩放图像并使其居中它将容器的大小调整为fill_parent的大小,它应该就是这样。

答案 3 :(得分:0)

您可以将图像设置为可绘制(不创建xhdpi,hdpi,mdpi,ldpi ...)(全局图像)。

然后,您可以为不同的屏幕尺寸创建4个相同的布局。您的所有布局都可以使用可绘制导演中的图像。因此,您可以轻松调整图像大小。