2010-02-10 85 views
10

我使用下面的代碼(從博客文章)不支持的參數調整圖像大小圖片大小錯誤:CGBitmapContextCreate:

if (inImage.size.width <= inImage.size.height) { 
    // Portrait 
    ratio = inImage.size.height/inImage.size.width; 
    resizedRect = CGRectMake(0, 0, width, width * ratio); 
} 
else { 
    // Landscape 
    ratio = inImage.size.width/inImage.size.height; 
    resizedRect = CGRectMake(0, 0, height * ratio, height); 
} 

CGImageRef   imageRef = [inImage CGImage]; 
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef); 

if (alphaInfo == kCGImageAlphaNone) 
    alphaInfo = kCGImageAlphaNoneSkipLast; 

CGContextRef bitmap = CGBitmapContextCreate(
              NULL, 
              resizedRect.size.width,  // width 
              resizedRect.size.height,  // height 
              CGImageGetBitsPerComponent(imageRef), // really needs to always be 8 
              4 * resizedRect.size.width, // rowbytes 
              CGImageGetColorSpace(imageRef), 
              alphaInfo 
              ); 

,但由於某種原因,根據大小,我嘗試調整到我得到生成以下錯誤

CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 32 bits/pixel; 3-component colorspace; kCGImageAlphaNoneSkipFirst; XXX bytes/row.

其中XXX根據哪個圖像而不同。

我創建的矩形是對圖像的比例,我從寬度/高度(取決於方面)和多個目標寬度/高度取比率。

以下是一些例子(X錯誤/犯規),調整大小的尺寸將是50XX或Xx50取決於方面:

Source 50x50 69x69 
430x320/ X 
240x320/ /
272x320/ /
480x419/ X 
426x320 X  X 
480x256 X  X 

回答

12

如果你寫thumbRect,你的意思resizedRectthumbRect不會發生。

我懷疑問題是resizedRect.size.width是非整數。請注意,這是浮點數。

CGBitmapContextCreate的width和bytesPerRow參數被聲明爲整數。當你傳遞一個浮點值時,例如這裏,它會被截斷。

假設resizedRect.size.width爲1.25。然後,你會最終傳遞1的寬度,並且floor(1.25 * 4)== 5作爲每行的字節數。這是不一致的。無論您傳遞的是每行字節的寬度,您總是希望傳遞四次。

順便說一下,您也可以將bytesPerRow保留爲0。然後系統選擇最好的bytesPerRow(通常大於寬度的4倍 - 填充以便對齊)。

+0

是(複製並粘貼錯誤將其格式化爲一個問題) 是的我同意resizedRect.size.width可能是一個浮點數。你能再解釋一下,我是否需要整數? – 2010-02-10 09:26:21

+0

請剛剛更新您的回覆,我只是將這3個值用於int,並對問題進行了排序。 (int)resizedRect.size.width等 – 2010-02-10 09:31:31

+0

我編輯了我的回覆更多的細節。 – Ken 2010-02-10 18:55:27