2010-07-14 188 views
5

我有一個位圖...如果位圖的高度大於maxHeight,或者寬度大於maxWidth,我想按比例調整圖像的大小,使其適合maxWidth X最大高度。這裏就是我想:按比例調整位圖的大小

BitmapDrawable bmp = new BitmapDrawable(getResources(), PHOTO_PATH); 

    int width = bmp.getIntrinsicWidth(); 
    int height = bmp.getIntrinsicHeight(); 

    float ratio = (float)width/(float)height; 

    float scaleWidth = width; 
    float scaleHeight = height; 

    if((float)mMaxWidth/(float)mMaxHeight > ratio) { 
     scaleWidth = (float)mMaxHeight * ratio; 
    } 
    else { 
     scaleHeight = (float)mMaxWidth/ratio; 
    } 

    Matrix matrix = new Matrix(); 
    matrix.postScale(scaleWidth, scaleHeight); 

    Bitmap out = Bitmap.createBitmap(bmp.getBitmap(), 
      0, 0, width, height, matrix, true); 

    try { 
     out.compress(Bitmap.CompressFormat.JPEG, 100, 
       new FileOutputStream(PHOTO_PATH)); 
    } 
    catch(FileNotFoundException fnfe) { 
     fnfe.printStackTrace(); 
    } 

我得到以下異常:

java.lang.IllegalArgumentException: bitmap size exceeds 32bits

什麼我錯在這裏做什麼?

+0

你能在這裏通過更正的代碼嗎?我得到同樣的例外 – Mahesh 2012-12-12 07:07:45

回答

8

您的scaleWidth和scaleHeight應該是比例因子(所以不是很大的數字),但是您的代碼似乎通過了您要查找的實際寬度和高度。所以你最終會大幅增加你的位圖的大小。

我認爲還有其他的代碼來衍生scaleWidth和scaleHeight的問題。一方面,你的代碼總是有scaleWidth = widthscaleHeight =高度,並且只改變其中的一個,所以你將會扭曲圖像的高寬比。如果你只是想調整圖像大小,那麼你應該只有一個scaleFactor

此外,爲什麼您的if語句有效地檢查了最大比率?你不應該檢查寬度> maxWidth高度> maxHeight

1

這是因爲scaleWidthscaleHeight的值過大,scaleWidthscaleHeight是意味着放大或縮小的比率,而不是widthheight,過大的速率導致bitmap大小超過32位

matrix.postScale(scaleWidth, scaleHeight); 
1

這就是我是如何做到的:

public Bitmap decodeAbtoBm(byte[] b){ 
    Bitmap bm; // prepare object to return 

    // clear system and runtime of rubbish 
    System.gc(); 
    Runtime.getRuntime().gc(); 

    //Decode image size only 
    BitmapFactory.Options oo = new BitmapFactory.Options(); 
    // only decodes size, not the whole image 
    // See Android documentation for more info. 
    oo.inJustDecodeBounds = true; 
    BitmapFactory.decodeByteArray(b, 0, b.length ,oo); 

    //The new size we want to scale to 
    final int REQUIRED_SIZE=200; 

    // Important function to resize proportionally. 
    //Find the correct scale value. It should be the power of 2. 
    int scale=1; 
    while(oo.outWidth/scale/2>=REQUIRED_SIZE 
      && oo.outHeight/scale/2>=REQUIRED_SIZE) 
      scale*=2; // Actual scaler 

    //Decode Options: byte array image with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize=scale; // set scaler 
    o2.inPurgeable = true; // for effeciency 
    o2.inInputShareable = true; 

    // Do actual decoding, this takes up resources and could crash 
    // your app if you do not do it properly 
    bm = BitmapFactory.decodeByteArray(b, 0, b.length,o2); 

    // Just to be safe, clear system and runtime of rubbish again! 
    System.gc(); 
    Runtime.getRuntime().gc(); 

    return bm; // return Bitmap to the method that called it 
}