0

几个小时以来,我一直在为此挠头。

我正在使用以下方法调整 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.size和决定image2.size。我试过翻转方法的调用顺序,第一个总是正确的。

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

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

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

4

1 回答 1

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;

}
于 2014-02-24T16:21:01.357 回答