尝试调整图像大小时出现CGBitmapContextCreate问题

时间:2010-05-17 00:23:02

标签: iphone cocoa cocoa-touch ipad core-graphics

当我尝试在尝试调整某些图像时尝试创建CGContextRef时,我遇到了一个问题:

有错误

Sun May 16 20:07:18 new-host.home app [7406] <Error>: Unable to create bitmap delegate device
Sun May 16 20:07:18 new-host.home app [7406] <Error>: createBitmapContext: failed to create delegate.

我的代码看起来像这样

     - (UIImage*) resizeImage:(UIImage*)originalImage withSize:(CGSize)newSize {
 CGSize originalSize = originalImage.size;
 CGFloat originalAspectRatio = originalSize.width / originalSize.height;

 CGImageRef cgImage = nil;
 int bitmapWidth = newSize.width;
 int bitmapHeight = newSize.height;
 CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
 CGContextRef context = CGBitmapContextCreate(nil, bitmapWidth, bitmapHeight, 8, bitmapWidth * 4, colorspace, kCGImageAlphaPremultipliedLast);



 if (context != nil) {
  // Flip the coordinate system
  //CGContextScaleCTM(context, 1.0, -1.0);
  //CGContextTranslateCTM(context, 0.0, -bitmapHeight);

  // Black background
  CGRect rect = CGRectMake(0, 0, bitmapWidth, bitmapHeight);
  CGContextSetRGBFillColor (context, 0, 0, 0, 1);
  CGContextFillRect (context, rect);

  // Resize box to maintain aspect ratio
  if (originalAspectRatio < 1.0) {
   rect.origin.y += (rect.size.height - rect.size.width / originalAspectRatio) * 0.5;
   rect.size.height = rect.size.width / originalAspectRatio;
  } else {
   rect.origin.x += (rect.size.width - rect.size.height * originalAspectRatio) * 0.5;
   rect.size.width = rect.size.height * originalAspectRatio;
  }

  CGContextSetInterpolationQuality(context, kCGInterpolationHigh);

  // Draw image
  CGContextDrawImage (context, rect, [originalImage CGImage]);

  // Get image
  cgImage = CGBitmapContextCreateImage (context);

  // Release context
  CGContextRelease(context);
 }
 CGColorSpaceRelease(colorspace);

 UIImage *result = [UIImage imageWithCGImage:cgImage];
 CGImageRelease (cgImage);
 return result;
}

2 个答案:

答案 0 :(得分:0)

您不能将nil作为CGBitmapContextCreate的第一个参数传递。为像素分配一些空间。想想可怜的像素。

答案 1 :(得分:0)

所以看起来我正在使用太大的图像。基本上我试图扩大10倍的规模似乎太多了。无论如何,就是这样。