从 iPhone 相机保存和裁剪 UIImage

Posted

技术标签:

【中文标题】从 iPhone 相机保存和裁剪 UIImage【英文标题】:Saving and cropping a UIImage from the iphone camera 【发布时间】:2014-07-14 07:02:06 【问题描述】:

我有以下代码:

    float photoWidth = photo.size.width;
    float photoHeight = photo.size.height;

    UIImage *picture = nil;

    if (photoWidth < photoHeight)
    
        // Portrait

        // Scale the photo down
        CGRect rect = CGRectMake(0.0, 0.0, 450.0, 600.0);
        UIGraphicsBeginImageContext( rect.size );
        [photo drawInRect:rect];
        picture = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
    else
    
        // Landscape

        // Crop off the edges
        float scale = photoHeight / photoWidth;

        float newWidth = photoHeight * scale;
        float newHeight = photoHeight;
        float newX = (newHeight - newWidth) / 2.0;
        float newY = 0.0;

        CGRect cropped = CGRectMake(newX, newY, newWidth, newHeight);

        CGImageRef imageRef = CGImageCreateWithImageInRect ([photo CGImage], cropped);
        UIImage * croppedPhoto = [UIImage imageWithCGImage: imageRef];
        CGImageRelease (imageRef);

        // Scale the photo down
        CGRect rect = CGRectMake(0.0, 0.0, 450.0, 600.0);
        UIGraphicsBeginImageContext( rect.size );
        [croppedPhoto drawInRect:rect];
        picture = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    

    NSData *photoData = UIImagePNGRepresentation(picture);

当我使用 photoData 并将其转换为 UIImage 时,纵向模式可以正常工作。但是横向模式有问题。

我正在尝试通过裁剪照片的左右边缘来使风景与我的肖像大小相同。

还注意到,如果我在拍照时翻转横向相机,方向会使我的照片上下颠倒。

我做错了吗?

谢谢。

【问题讨论】:

【参考方案1】:

尝试改变

[UIImage imageWithCGImage: imageRef];

[UIImage imageWithCGImage:imageRef scale: photo.scale orientation:UIImageOrientationUp];

[UIImage imageWithCGImage:imageRef scale: photo.scale orientation:photo.imageOrientation];

【讨论】:

我仍然无法让它工作。根据我握风景相机的方式,它仍然是颠倒的,第二个矩形是关闭的。

以上是关于从 iPhone 相机保存和裁剪 UIImage的主要内容,如果未能解决你的问题,请参考以下文章