1

我已经写了一个类别UIImage来调整图像大小,比如 iphone 照片应用程序。

尽管插值设置为高,但图像看起来并不像照片应用程序中的那样。相反,它看起来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:是否使用高插值没有区别。也许我做错了什么。

在此先感谢您的帮助!

4

2 回答 2

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);
于 2012-12-21T19:29:45.853 回答
0

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

CGContextSetShouldAntialias(context, NO);

希望这可以帮助。

于 2012-12-21T19:14:54.967 回答