2011-03-08 38 views
5

我一直在嘗試這一段時間,我想從Bitmap創建壁紙。假設所需的壁紙大小爲320x480,並且源圖像大小爲2048x2048。Android中的剪裁合身圖像

我不確定crop-to-fit是否合適,但我希望實現的是獲得與所需壁紙大小(320x480)相等比例的大部分圖片。

所以在這種情況下,我想從源Bitmap獲得2048x1365或(1365.333 ...的確切值),並將其縮小到320x480。

,我曾嘗試的技術是:

1)裁剪位圖入2048x1365第一

bm = Bitmap.createBitmap(bm, xOffset, yOffset, 2048, 1365); 

2)規模它下降到小320x480

bm = Bitmap.createScaledBitmap(bm, 320, 480, false); 

它生產OutOfMemory錯誤。

有什麼辦法可以達到這個目的嗎?

問候,

dezull

+0

我覺得你的標題會被更好地描述爲「規模以適應的,保持相同的寬高比」 – 2011-03-08 00:26:46

+0

謝謝,那還不如適合作爲標題,不過說真的,我想要什麼如果你解決了這個問題,那麼請分享你的解決方案,以達到「縮放」和「裁剪」圖像的某個區域以適應 – dezull 2011-03-08 01:30:12

+0

。 – Tushar 2013-03-22 07:22:10

回答

15

由於開源,我發現從Android圖庫源代碼here答案在行230 :-D

croppedImage = Bitmap.createBitmap(mOutputX, mOutputY, Bitmap.Config.RGB_565); 
Canvas canvas = new Canvas(croppedImage); 

Rect srcRect = mCrop.getCropRect(); 
Rect dstRect = new Rect(0, 0, mOutputX, mOutputY); 

int dx = (srcRect.width() - dstRect.width())/2; 
int dy = (srcRect.height() - dstRect.height())/2; 

// If the srcRect is too big, use the center part of it. 
srcRect.inset(Math.max(0, dx), Math.max(0, dy)); 

// If the dstRect is too big, use the center part of it. 
dstRect.inset(Math.max(0, -dx), Math.max(0, -dy)); 

// Draw the cropped bitmap in the center 
canvas.drawBitmap(mBitmap, srcRect, dstRect, null); 
+3

我有你的同樣的問題。你能解釋什麼是mOutputX,mCrop ...或更好,你能寫和示例函數比接收位圖並返回裁剪和縮放的位圖?非常感謝。 – Ton 2012-06-07 19:24:03

+0

這些是輸出寬度和高度。這個確切的主題已添加到Android開發人員網站http://developer.android.com/training/displaying-bitmaps/load-bitmap.html – dezull 2012-06-14 15:38:16

+0

鏈接不再工作。 – Warpzit 2013-11-05 10:07:57

0

這裏是讓你最那裏的方式回答: How to crop an image in android?

+0

謝謝,但不是我正在尋找的解決方案。看到我自己的答案,只需使用Rect來縮放它。它不會產生OOM :-) – dezull 2011-03-08 01:28:08

9

我知道這是一個令人難以置信的晚回覆,但事端摹像這樣也許:

public static Bitmap scaleCropToFit(Bitmap original, int targetWidth, int targetHeight){ 
    //Need to scale the image, keeping the aspect ration first 
    int width = original.getWidth(); 
    int height = original.getHeight(); 

    float widthScale = (float) targetWidth/(float) width; 
    float heightScale = (float) targetHeight/(float) height; 
    float scaledWidth; 
    float scaledHeight; 

    int startY = 0; 
    int startX = 0; 

    if (widthScale > heightScale) { 
     scaledWidth = targetWidth; 
     scaledHeight = height * widthScale; 
     //crop height by... 
     startY = (int) ((scaledHeight - targetHeight)/2); 
    } else { 
     scaledHeight = targetHeight; 
     scaledWidth = width * heightScale; 
     //crop width by.. 
     startX = (int) ((scaledWidth - targetWidth)/2); 
    } 

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(original, (int) scaledWidth, (int) scaledHeight, true); 

    Bitmap resizedBitmap = Bitmap.createBitmap(scaledBitmap, startX, startY, targetWidth, targetHeight); 
    return resizedBitmap; 
}