iPhone - Mirroring back a picture taken from the f

2019-02-01 02:17发布

When using the front camera of the iPhone 4 to take a picture, the taken picture is mirrored compared with what you see on the iPhone screen. How may I restore the "on screen" view of the UIImage (not the UIImageView), and be able to save it like this ?

I tried :

UIImage* transformedImage = [UIImage imageWithCGImage:pickedImage.CGImage scale:1.0 orientation:UIImageOrientationLeftMirrored];
UIImageWriteToSavedPhotosAlbum (transformedImage, self, @selector(photoSaved:didFinishSavingWithError:contextInfo:), nil);

then putting it on screen. It is nearly the same as seen on screen, but the saved image is distorted.

So... How may I restore the "on screen" view of the UIImage (not the UIImageView), and be able to save it like this ?

I also tried this way :

UIImage* pickedImage = [[info objectForKey:UIImagePickerControllerOriginalImage] retain];
UIImage* transformedImage;

CGSize imageSize = pickedImage.size;
UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1.0);
GContextRef ctx = UIGraphicsGetCurrentContext();

CGContextRotateCTM(ctx, 3.14);  // rotate by 180°
CGContextScaleCTM(ctx, 1.0, -1.0); // flip vertical
CGContextDrawImage(ctx, CGRectMake(0.0, 0.0, imageSize.width, imageSize.height), pickedImage.CGImage);
transformedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

But that just gives a black image.

8条回答
迷人小祖宗
2楼-- · 2019-02-01 02:59

I know this question was already answered, but the answer above didn't work for me so in case there are others...

UIImage *theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (picker.cameraDevice == UIImagePickerControllerCameraDeviceFront) {
        CGSize imageSize = theImage.size;
        UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1.0);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextRotateCTM(ctx, M_PI/2);
        CGContextTranslateCTM(ctx, 0, -imageSize.width);
        CGContextScaleCTM(ctx, imageSize.height/imageSize.width, imageSize.width/imageSize.height);
        CGContextDrawImage(ctx, CGRectMake(0.0, 0.0, imageSize.width, imageSize.height), theImage.CGImage);
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

and newImage is your new image with the up orientation

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-01 03:00

A slightly simpler answer updated for Swift 3:

func flipImage(image: UIImage) -> UIImage {
    guard let cgImage = image.cgImage else {
        // Could not form CGImage from UIImage for some reason.
        // Return unflipped image
        return image
    }
    let flippedImage = UIImage(cgImage: cgImage, 
                               scale: image.scale, 
                               orientation: .leftMirrored)
    return flippedImage
}
查看更多
登录 后发表回答