我搜索了SO和一些网络教程,将这个IBAction
放在一起,编辑了UIImage的像素。编辑它应该使照片灰度,但它也旋转图像,我不明白为什么。其他人能找出原因吗?谢谢!为什么编辑像素后我的UIImage旋转?
- (IBAction)grayscale:(id)sender {
CGContextRef ctx;
CGImageRef imageRef = [self.workingImage CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
_text1.text = [NSString stringWithFormat: @"%d", width];
_text2.text = [NSString stringWithFormat: @"%d", height];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
int byteIndex = 0;
for (int ii = 0 ; ii < width * height ; ++ii)
{
int outputColor = (rawData[byteIndex] + rawData[byteIndex+1] +
rawData[byteIndex+2])/3;
rawData[byteIndex] = (char) (outputColor);
rawData[byteIndex+1] = (char) (outputColor);
rawData[byteIndex+2] = (char) (outputColor);
byteIndex += 4;
}
ctx = CGBitmapContextCreate(rawData,
CGImageGetWidth(imageRef),
CGImageGetHeight(imageRef),
8,
CGImageGetBytesPerRow(imageRef),
CGImageGetColorSpace(imageRef),
kCGImageAlphaPremultipliedLast);
imageRef = CGBitmapContextCreateImage (ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];
CGContextRelease(ctx);
self.workingImage = rawImage;
[_theImage setImage:_workingImage];
free(rawData);
}
检查你的形象定位:\t UIImageOrientation东方= image.imageOrientation; 如果不是1,您可能需要先旋转它。 – Thorsten
感谢您的建议... orient = 1!你能告诉我如何旋转它吗? – jake9115
我试着用'imageView.transform = CGAffineTransformMakeRotation(3.14/2)来定位UIImageView; ',这显示了正确的方向图片,但我的照片现在被挤压为横向而不是其原始的肖像! – jake9115