UIImage+MLKit.m 2.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//
//  UIImage.m
//  MediaLibraryKit
//
//  Created by Felix Paul Kühne on 29/05/15.
//  Copyright (c) 2015 VideoLAN. All rights reserved.
//

#import "UIImage+MLKit.h"
#import <AVFoundation/AVFoundation.h>

@implementation UIImage (MLKit)

+ (CGSize)preferredThumbnailSizeForDevice
{
    CGFloat thumbnailWidth, thumbnailHeight;
    /* optimize thumbnails for the device */
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
19 20
        thumbnailWidth = 272.;
        thumbnailHeight = 204.;
21
    } else {
22 23
        thumbnailWidth = 240.;
        thumbnailHeight = 135.;
24 25 26 27
    }
    return CGSizeMake(thumbnailWidth, thumbnailHeight);
}

28 29 30 31 32
+ (UIImage *)scaleImage:(UIImage *)image toFitRect:(CGRect)rect {
    return [self scaleImage:image toFitRect:rect scale:[UIScreen mainScreen].scale];
}

+ (UIImage *)scaleImage:(UIImage *)image toFitRect:(CGRect)rect scale:(CGFloat)scale
33 34 35 36 37 38 39 40 41 42
{
    CGRect destinationRect = AVMakeRectWithAspectRatioInsideRect(image.size, rect);

    CGImageRef cgImage = image.CGImage;
    size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
    size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
    CGColorSpaceRef colorSpaceRef = CGImageGetColorSpace(cgImage);
    CGBitmapInfo bitmapInfoRef = CGImageGetBitmapInfo(cgImage);

    CGContextRef contextRef = CGBitmapContextCreate(NULL,
43 44
                                                    destinationRect.size.width*scale,
                                                    destinationRect.size.height*scale,
45 46 47 48 49 50 51 52
                                                    bitsPerComponent,
                                                    bytesPerRow,
                                                    colorSpaceRef,
                                                    bitmapInfoRef);

    CGContextSetInterpolationQuality(contextRef, kCGInterpolationLow);

    CGContextDrawImage(contextRef, (CGRect){CGPointZero, destinationRect.size}, cgImage);
Tobias's avatar
Tobias committed
53
    CGImageRef imageRef = CGBitmapContextCreateImage(contextRef);
54
    UIImage *scaledImage = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
Tobias's avatar
Tobias committed
55 56 57
    CGImageRelease(imageRef);
    CGContextRelease(contextRef);
    return scaledImage;
58 59 60
}

@end