UIGraphicsBeginImageContextWithOptions和UIImageJPEGRepresentation不能很好地协同工作

时间:2011-08-07 22:54:06

标签: iphone objective-c uiimagejpegrepresentation

所以我有这个代码来创建UIImage:

UIGraphicsBeginImageContextWithOptions(border.frame.size, YES, 0);
[border.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

此时,图像上的尺寸正确,为80x100。

然后它运行此代码:

NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);

图像的NSData返回尺寸为160x200的图像 - 是应有的两倍。

很清楚原因是这一行:

UIGraphicsBeginImageContextWithOptions(border.frame.size, YES, 0);

结尾的0是比例,因为它是0,它取决于设备的比例因子。我保持这种方式来保持清晰的形象。然而,当我将图像设置为1时,尽管图像保持其应该的大小,但它不会出现视网膜质量。我想要做的是保持视网膜质量,但也保持适当的大小。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

在调用UIImageJPEGRepresentation

之前尝试调整UIImage的大小
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    CGImageRef imageRef = image.CGImage;

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);

    CGContextConcatCTM(context, flipVertical);  
    // Draw into the context; this scales the image
    CGContextDrawImage(context, newRect, imageRef);

    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    CGImageRelease(newImageRef);
    UIGraphicsEndImageContext();    

    return newImage;
}

if([UIScreen mainScreen].scale > 1)
    {
        thumbnailImage = [self thumbnailImage newSize:CGSizeMake(thumbnailImage.size.width/[UIScreen       mainScreen].scale, thumbnailImage.size.height/[UIScreen mainScreen].scale)];
    }

答案 1 :(得分:0)

- (UIImage *)imageWithImage{
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}