CGBitmapContextCreate:无效的数据字节/行

时间:2014-06-09 16:26:10

标签: ios

我正在尝试调整图像大小,然后再将其显示回用户。

我得到的错误是错误:CGBitmapContextCreate:无效的数据字节/行:对于8个整数位/组件,3个组件,至少5504,kCG​​ImageAlphaNoneSkipFirst。

我也得到错误:CGContextDrawImage:无效的上下文0x0。

这是我使用的代码:

    -(UIImage*)imageByScalingToSize:(CGRect)target :(UIImage*)old
{
    UIImage* sourceImage = old;
    CGFloat targetWidth = target.size.width + 10;
    CGFloat targetHeight = target.size.height;
    CGFloat x = target.origin.x;
    CGFloat y = target.origin.y - 105;

    CGImageRef imageRef = [sourceImage CGImage];
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);

    if (bitmapInfo == kCGImageAlphaNone) {
        bitmapInfo = kCGImageAlphaNoneSkipLast;
    }   CGContextRef bitmap;

    if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) {
        bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);    
    } 
    else {
        bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);      
    }

    if (sourceImage.imageOrientation == UIImageOrientationLeft) {
        CGContextRotateCTM (bitmap, radians(90));
        CGContextTranslateCTM (bitmap, 0, -targetHeight);     
    } 
    else if (sourceImage.imageOrientation == UIImageOrientationRight) {
        CGContextRotateCTM (bitmap, radians(-90));
        CGContextTranslateCTM (bitmap, -targetWidth, 0);     
    } 
    else if (sourceImage.imageOrientation == UIImageOrientationUp) {
        // NOTHING
    } 
    else if (sourceImage.imageOrientation == UIImageOrientationDown) {
        CGContextTranslateCTM (bitmap, targetWidth, targetHeight);
        CGContextRotateCTM (bitmap, radians(-180.));
    }

    CGContextDrawImage(bitmap, CGRectMake(x, y, targetWidth, targetHeight), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage* newImage = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);
    CGImageRelease(ref);

    return newImage; 
}

1 个答案:

答案 0 :(得分:8)

试试这个:

bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), 0, colorSpaceInfo, bitmapInfo);    
  

bitsPerComponent

     

内存中像素的每个分量使用的位数。例如,对于32位像素格式和RGB颜色空间,您可以为每个组件指定8位的值。有关支持的像素格式列表,请参阅“Quartz 2D编程指南”的“图形上下文”一章中的“支持的像素格式”。

如果这不能改善,请发布CGImageGetBitsPerComponent(imageRef)CGImageGetBytesPerRow(imageRef)的值。