【问题标题】:iOS: not getting correct result with CGBitmapContextCreate in method calliOS:在方法调用中使用 CGBitmapContextCreate 没有得到正确的结果
【发布时间】:2014-02-24 16:15:54
【问题描述】:

几个小时以来,我一直在为这个问题摸不着头脑。

我正在使用以下方法调整 2 张图像的大小。一个接一个:

CGImageRef imageReference = [image CGImage];
bytes = malloc(width * height * 4); 

NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(bytes, width, height, bitsPerComponent,
                                bytesPerRow, colorSpaceReference,
                                kCGImageAlphaPremultipliedLast);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageReference); 
CGImageRelease(imageReference);
CGContextRelease(context);

它工作正常,没问题 - 但只有一张图片。如果我再次调用这个方法,例如:

[self resizeImageWithSize:imageSize];  //this is OK.
[self resizeImageWithSize:imageSize]; //this would not come out right

其中图像大小由以下因素决定:image1.sizeimage2.size。我试过翻转方法的调用顺序,第一个总是正确的。

它们不是太大,400 x 300、300 x 360。我只想将一个调整为 200 x 200,另一个调整为 150 x 150。而且它们只是 png。

它有效,但是如果我再次调用此方法,则第二张图像是错误的。错误的是它像纸上的水渍一样弄乱了像素。有时它甚至变得无法辨认。

我是否遗漏了一些非常明显的东西?我试过free(bytes);,我认为这里不需要,但为了尝试,但它仍然没有带来任何东西。我是否没有正确释放/释放某些东西,以便第二次调用该方法时,旧字节数据仍然存在?我只是在这里猜测。我正在使用 ARC。

【问题讨论】:

    标签: ios cgimage cgimageref cgbitmapcontextcreate


    【解决方案1】:

    我正在使用这种方法,它就像一个魅力希望这会有所帮助:

    - (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)newSize
    {
        UIImage *newImage = nil;
    
        UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
        [image drawInRect:CGRectMake(0.0,
                                     0.0,
                                     newSize.width,
                                     newSize.height)];
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    
    }
    

    【讨论】:

    • 谢谢。但是我还是希望知道为什么我上面的方法是错误的。 +1,但是,为了分享一个漂亮而干净的方法。
    • @Unheilig,尝试将 UIGraphicsBeginImageContext(),放在您的代码和 UIGraphicsEndImageContext() 之前;在你的代码之后。告诉我它是否有效,我有兴趣:)
    • 反馈:非常感谢提示,但它并没有解决它。
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多