美文网首页
iOS 矫正图片方向

iOS 矫正图片方向

作者: 假如兔子失了尾 | 来源:发表于2021-01-04 10:23 被阅读0次

//矫正相册获取的照片资源位置倾斜

+ (UIImage*)fixOrientation:(UIImage*)image {

    if (image.imageOrientation == UIImageOrientationUp)

        returnimage;

    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (image.imageOrientation) {

        case UIImageOrientationDown:

        case UIImageOrientationDownMirrored:

            transform =CGAffineTransformTranslate(transform, image.size.width, image.size.height);

            transform =CGAffineTransformRotate(transform,M_PI);

            break;

        case UIImageOrientationLeft:

        case UIImageOrientationLeftMirrored:

            transform =CGAffineTransformTranslate(transform, image.size.width,0);

            transform =CGAffineTransformRotate(transform,M_PI_2);

            break;

        case UIImageOrientationRight:

        case UIImageOrientationRightMirrored:

            transform =CGAffineTransformTranslate(transform,0, image.size.height);

            transform =CGAffineTransformRotate(transform, -M_PI_2);

            break;

        default:

            break;

    }

    switch (image.imageOrientation) {

        case UIImageOrientationUpMirrored:

        case UIImageOrientationDownMirrored:

            transform =CGAffineTransformTranslate(transform, image.size.width,0);

            transform =CGAffineTransformScale(transform, -1,1);

            break;

        case UIImageOrientationLeftMirrored:

        case UIImageOrientationRightMirrored:

            transform =CGAffineTransformTranslate(transform, image.size.height,0);

            transform =CGAffineTransformScale(transform, -1,1);

            break;

        default:

            break;

    }

    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,

                                             CGImageGetBitsPerComponent(image.CGImage),0,

                                             CGImageGetColorSpace(image.CGImage),

                                             CGImageGetBitmapInfo(image.CGImage));

    CGContextConcatCTM(ctx, transform);

    switch (image.imageOrientation) {

        case UIImageOrientationLeft:

        case UIImageOrientationLeftMirrored:

        case UIImageOrientationRight:

        case UIImageOrientationRightMirrored:

            // Grr...

            CGContextDrawImage(ctx,CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);

            break;

        default:

            CGContextDrawImage(ctx,CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);

            break;

    }

    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);

    UIImage *img = [UIImage imageWithCGImage:cgimg];

    CGContextRelease(ctx);

    CGImageRelease(cgimg);

    return img;

}

相关文章

网友评论

      本文标题:iOS 矫正图片方向

      本文链接:https://www.haomeiwen.com/subject/aaimoktx.html