ios调整大小的图像大小 - 虽然高插值模糊

时间:2012-12-21 13:04:36

标签: iphone ios ipad uiimage image-resizing

我在UIImage上写了一个类别,用于调整iphone照片应用等图片的大小。

虽然Interpolation设置为高,但图像看起来并不像照片应用程序中的图像。相反,它会显示unsharpblurry

这是我做的:

    - (UIImage *)resizeImageProportionallyIntoNewSize:(CGSize)newSize;
    {
    CGFloat scaleWidth = 1.0f;
    CGFloat scaleHeight = 1.0f;

    NSLog(@"Origin Size = %@", NSStringFromCGSize(self.size));

    if (CGSizeEqualToSize(self.size, newSize) == NO) {

        //calculate "the longer side"
        if(self.size.width > self.size.height) {
            scaleWidth = self.size.width / self.size.height;
        } else {
            scaleHeight = self.size.height / self.size.width;
        }
    }    

    // now draw the new image in a context with scaling proportionally
    UIImage *sourceImage = self;
    UIImage *newImage = nil;

    //now we create a context in newSize and draw the image out of the bounds of the context to get
    //an proportionally scaled image by cutting of the image overlay
    if([[UIScreen mainScreen] scale] == 2.00) {
         UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
    }
    UIGraphicsBeginImageContext(newSize);
    // Set the quality level to use when rescaling
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);

    //Center image point so that on each egde is a little cutoff
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.size.width  = (int) newSize.width * scaleWidth;
    thumbnailRect.size.height = (int) newSize.height * scaleHeight;
    thumbnailRect.origin.x = (int) (newSize.width - thumbnailRect.size.width) * 0.5;
    thumbnailRect.origin.y = (int) (newSize.height - thumbnailRect.size.height) * 0.5;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if(newImage == nil) NSLog(@"could not scale image");


    return newImage ;
}

BTW:使用高插值没有区别。也许我做错了什么。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

制作缩略图的最佳方法是使用Image I / O Framework让系统为您完成。唯一的技巧是,因为你使用CGImage,你必须考虑屏幕分辨率:

CGImageSourceRef src = CGImageSourceCreateWith... // whatever
CGFloat scale = [UIScreen mainScreen].scale;
CGFloat w = // maximum size, multiplied by the scale
NSDictionary* d = 
    [NSDictionary dictionaryWithObjectsAndKeys:
     (id)kCFBooleanTrue, kCGImageSourceShouldAllowFloat,
     (id)kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform,
     (id)kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways,
     [NSNumber numberWithInt:(int)w], kCGImageSourceThumbnailMaxPixelSize,
     nil];
CGImageRef imref = 
    CGImageSourceCreateThumbnailAtIndex(src, 0, (__bridge CFDictionaryRef)d);
UIImage* im = 
    [UIImage imageWithCGImage:imref scale:scale orientation:UIImageOrientationUp];
CFRelease(imref); CFRelease(src);

答案 1 :(得分:0)

如果不清晰/模糊,您应该尝试通过以下方式关闭消除锯齿:

CGContextSetShouldAntialias(context, NO);

希望这会有所帮助。