UIImageJPEGRepresentation在Retina屏幕上提供2倍大小的图像

3

我有这段代码,它创建了一张图片,然后添加了一些效果并将其缩小以制作出largeThumbnail

UIImage *originalImage = [UIImage imageWithData:self.originalImage];
thumbnail = createLargeThumbnailFromImage(originalImage);

NSLog(@"thumbnail: %f", thumbnail.size.height);
NSData *thumbnailData = UIImageJPEGRepresentation(thumbnail, 1.0);

后续:

UIImage *image = [UIImage imageWithData:self.largeThumbnail];
NSLog(@"thumbnail 2: %f", image.size.height);

NSLog返回:

thumbnail: 289.000000
thumbnail 2: 578.000000

如您所见,当它将图像从数据转换回来时,会使其大小增加两倍。有什么想法是为什么会发生这种情况吗?

大缩略图代码:

UIImage *createLargeThumbnailFromImage(UIImage *image) {
    UIImage *resizedImage;

        resizedImage = [image imageScaledToFitSize:LARGE_THUMBNAIL_SIZE];

    CGRect largeThumbnailRect = CGRectMake(0, 0, resizedImage.size.width, resizedImage.size.height);

    UIGraphicsBeginImageContextWithOptions(resizedImage.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    //Image
    CGContextTranslateCTM(context, 0, resizedImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, largeThumbnailRect, resizedImage.CGImage);

    //Border
    CGContextSaveGState(context);
    CGRect innerRect = rectForRectWithInset(largeThumbnailRect, 1.5);
    CGMutablePathRef borderPath = createRoundedRectForRect(innerRect, 0);
    CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
    CGContextSetLineWidth(context, 3);
    CGContextAddPath(context, borderPath);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);

    UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return thumbnail;
}

你有什么想法为什么会发生这种情况吗?你尝试过自己调试吗? - jscs
我添加了额外的NSLog,发现问题出现在图像从NSData转换回来的那一点。 - Andrew
1个回答

6

尝试替换加载第二张图片的部分:

UIImage *image = [UIImage imageWithData:self.largeThumbnail];

使用这个:

UIImage *jpegImage = [UIImage imageWithData:self.largeThumbnail];
UIImage *image = [UIImage imageWithCGImage:jpegImage.CGImage scale:originalImage.scale orientation:jpegImage.imageOrientation];

在这里发生的情况是图像比例没有设置,因此您会得到双倍的图像尺寸。

我遇到了同样的问题(从NSData *转换回来时得到2倍图像)。你能详细说明一下吗?对我来说,originalImage.scale返回1,所以这个解决方案对我不起作用。 - mostruash
比例尺没有设置,所以您会得到双倍的图像尺寸。这行代码对我很有帮助...谢谢。 - IKKA
1
我在调用UIGraphicsBeginImageContextWithOptions时将“0”作为比例传递以创建缩放图像。传递originalImage.scale解决了问题。谢谢! - PaulG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接