-(UIImage * ) flipImage: (UIImage * ) imag {
CGImageRef img1 = imag.CGImage;
CFDataRef dataref = CopyImagePixels(img1);
UInt8 * data = (UInt8 * ) CFDataGetBytePtr(dataref);
int length = CFDataGetLength(dataref);
size_t width = CGImageGetWidth(img1);
size_t height = CGImageGetHeight(img1);
size_t bytesPerRow = CGImageGetBytesPerRow(img1);
size_t bitsPerComponent = CGImageGetBitsPerComponent(img1);
size_t bitsPerPixel = CGImageGetBitsPerPixel(img1);
NSLog(@"size %d x %d pixel:%d component :%d length:%d", (int) width * 4, (int) height, (int) bitsPerPixel, (int) bitsPerComponent, length);
int temp;
for (int i = 0; i < height / 2; i++) {
for (int j = 0; j < (width * 4); j++) {
temp = (int) data[i * width * 4 + j];
NSLog(@"first data :%ld second data:%ld", i * width * 4 + j, width * 4 * (height - 1 - i) + j);
data[i * width * 4 + j] = data[(width * 4 * (height - 1 - i)) + j];
data[(width * 4 * (height - 1 - i)) + j] = (size_t) temp;
}
}
CGColorSpaceRef colorspace = CGImageGetColorSpace(img1);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(img1);
CFDataRef newData = CFDataCreate(NULL, data, length);
CGDataProviderRef provider = CGDataProviderCreateWithCFData(newData);
CGImageRef newImg = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorspace, bitmapInfo, provider, NULL, true, kCGRenderingIntentDefault);
//[imvcomment setImage:[UIImage imageWithCGImage:newImg]];
return [UIImage imageWithCGImage: newImg];
CGImageRelease(newImg);
CGDataProviderRelease(provider);
}
CFDataRef CopyImagePixels(CGImageRef inImage) {
return CGDataProviderCopyData(CGImageGetDataProvider(inImage));
}
问问题
604 次
3 回答
3
你不能用这里imageWithCGImage:scale:orientation:
描述的一次调用来替换所有这些讨厌的代码吗?
UIImage *flipped = [UIImage imageWithCGImage:imag.CGImage scale:1.0 orientation:UIImageOrientationDown];
您可能需要将方向值更改为不同的值,具体取决于您之后的内容 - “翻转”有点模棱两可。
于 2012-10-16T06:07:18.387 回答
0
您的代码没有任何问题,我实现了您的代码并获得了翻转图像。
这是我的代码。
UIImage *imgg = [UIImage imageNamed:@"route.png"];
UIImageView *image = [[UIImageView alloc]init];
image.frame=CGRectMake(50, 50, 100, 50);
[self.view addSubview:image];
image.image = [self flipImage:imgg];
于 2012-10-16T06:47:50.600 回答
0
你得到每行的字节数,但你没有使用它。图像可能在每行的末尾有额外的填充。(这在具有奇数宽度的图像中很常见。)你可以这样写:
for (i = 0; i < height / 2; i++)
{
for (j = 0; j < width; j++)
{
temp = (int)data [ i * bytesPerRow + j ];
data[i * bytesPerRow + j] = data[(bytesPerRow * (height - 1 - i)) + j];
data[(bytesPerRow * (height - 1 - i)) + j] = (size_t) temp;
}
}
此外,您可能想要验证它bitsPerPixel
是否适合 int。如果图像中有 4 个浮点通道,则可能没有。
于 2012-10-16T05:15:23.113 回答