2013년 9월 8일 일요일

image Util 기능



//이미지 비율을 유지하면서 최대 가로사이즈보다 작은 이미지 사이즈
+ (CGSize)getScaledImageSize:(UIImage *)image scaledToMaxWidth:(CGFloat)maxWidth
{
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;
    
    CGFloat scaleFactor=1;
    
    if (oldWidth > maxWidth) {
        scaleFactor = maxWidth / oldWidth;
    } else {
        //scaleFactor = height / oldHeight;
        return image.size;
    }
    
    CGFloat newHeight = oldHeight * scaleFactor;
    CGFloat newWidth = oldWidth * scaleFactor;
    CGSize newSize = CGSizeMake(newWidth, newHeight);
    return newSize;
}

//이미지 비율을 유지하면서 최대 가로 or 높이보다 작은 이미지 사이즈 생성
+ (UIImage *)getScaledImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height {
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;
    
    CGFloat scaleFactor=1;
    
    if (oldWidth > width) {
        scaleFactor = width / oldWidth;
    } else if(height){
        scaleFactor = height / oldHeight;
    } else  //oldWidth<width and height==0이면, scale하지 않음.
        return image;
    
    CGFloat newHeight = oldHeight * scaleFactor;
    CGFloat newWidth = oldWidth * scaleFactor;
    
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [image drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


//JPEG 이미지로 저장
UIImageJPEGRepresentation(scaledImage, 0.5);

//PNG 이미지로 저장
UIImagePNGRepresentation(scaledImage);




//이미지(썸네일) 캐슁 하는 방법

NSMutableDictionary *thumbnailCache_ = nil;


+ (void)initThumbnailCache {
    thumbnailCache_ = [[NSMutableDictionary alloc] initWithCapacity:20];
}


+ (UIImage *)addThumbnailToCache:(NSString *)path {
    if ([thumbnailCache_ count] >= 20) {
        id key = [[thumbnailCache_ allKeys] objectAtIndex:0];
        [thumbnailCache_ removeObjectForKey:key];
    }
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    if (image) {
        [thumbnailCache_ setObject:image forKey:path];
        return image;
    }
    
    return nil;
}


+ (UIImage *)cachedThumbnail:(NSString *)fileName {
    UIImage *image = [thumbnailCache_ objectForKey:fileName];
    if (image == nil) {
        image = [Util addThumbnailToCache:fileName];
        //NSLog(@"load file image (%@)",fileName);
    } else {
        //NSLog(@"load cached image (%@)",fileName);
    }
    
    return image;
}

//실제 사용방법

NSString *imgName = @"실제 이미지 경로(이미지 이름 포함)";


img = [Util cachedThumbnail:imgName];


댓글 없음:

댓글 쓰기