0

我有一些文件大小(例如 1000x1000)。

我想加载它并使它变小

UIImage *newImage = [UIImage imageWithCGImage:[UIImage imageWithContentsOfFile:filename].CGImage scale:(1.0f / scale) orientation:UIImageOrientationUp];
NSLog(newImage size: %f, %f", newImage.size.width, newImage.size.height);
// shows correct scaled size -> 50, 50

然后我想保存这个缩放的图像

NSData* imageData = UIImageJPEGRepresentation(newImage, 1.0);
[imageData writeToFile:otherFileName atomically:NO];

我很困惑地看到新图像是以第一个起始尺寸(1000x1000)保存的。

这怎么可能,该怎么办?

4

2 回答 2

2

只需制作一种方法:

-(UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {

    float width = newSize.width;
    float height = newSize.height;

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect: CGRectMake(0, 0, width, height)];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return smallImage;
}

并像这样设置您需要的大小:

UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)]; // i have taken 150 you can change value here
于 2013-03-07T08:51:27.707 回答
1

您可以使用波纹管方法创建具有较小尺寸的图像而没有划痕图像:-

您可以调用以下方法:-

newImage=[self scaleImage:newImage toSize:CGSizeMake(250, 250)];


- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
    CGSize scaledSize = newSize;
    float scaleFactor = 2.0;
    if( image.size.width > image.size.height ) {
        scaleFactor = image.size.width / image.size.height;
        scaledSize.width = newSize.width;
        scaledSize.height = newSize.height / scaleFactor;
    }
    else {
        scaleFactor = image.size.height / image.size.width;
        scaledSize.height = newSize.height;
        scaledSize.width = newSize.width / scaleFactor;
    }

    UIGraphicsBeginImageContextWithOptions( scaledSize, NO, 0.0 );
    CGRect scaledImageRect = CGRectMake( 0.0, 0.0, scaledSize.width, scaledSize.height );
    [image drawInRect:scaledImageRect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return scaledImage;
}
于 2013-03-07T08:49:15.173 回答