在 Xcode 中通过 HTTP POST 发送图像之前减小图像的大小

Reduce the size of image before it is sent in an HTTP POST in Xcode

我有一个程序可以将通过我的 iPad 应用拍摄的图像发送到数据库(下面的代码)。有没有办法在发布之前缩小图片的大小?

UIImage *image = [photos objectAtIndex:i];
NSData *imageData = UIImageJPEGRepresentation(image, 10);

// setting up the request object
NSMutableURLRequest *photoRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:photoPostString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [photoRequest setHTTPMethod:@"POST"];


NSMutableURLRequest *photoRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:photoPostString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[photoRequest setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
photoRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"1234.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[photoRequest setHTTPBody:body];

您可以在上传前调整 UIImage 的大小。

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

或一些帮手 类:

https://github.com/AliSoftware/UIImage-Resize

https://github.com/mustangostang/UIImage-ResizeMagick

https://github.com/AliSoftware/UIImage-Resize

将此类别("UIImage+Resize.h" & "UIImage+Resize.m")添加到您的项目中。

UIImage *newImage = [existingImage resizedImageToSize:CGSizeMake(128, 128)];