【问题标题】:Saving and cropping a UIImage from the iphone camera从 iPhone 相机保存和裁剪 UIImage
【发布时间】: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 时,纵向模式可以正常工作。但是横向模式有问题。

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

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

我做错了吗?

谢谢。

【问题讨论】:

    标签: ios ios7 uiimage cgimageref uigraphicscontext


    【解决方案1】:

    尝试改变

    [UIImage imageWithCGImage: imageRef];
    

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

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

    【讨论】:

    • 我仍然无法让它工作。根据我握风景相机的方式,它仍然是颠倒的,第二个矩形是关闭的。
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2021-11-29
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    相关资源
    最近更新 更多