2

我编写了一个 iOS 方法来将所选图像上传到 Web 服务器,因此:

NSData *imageData = UIImagePNGRepresentation(imageView.image);
NSString *urlString = @"http://awebserversomewher.com/upload.php";

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

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

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"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]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"%@",returnString);

但是,在提交此图像之前,我想调整它的大小以使其更容易和更快地上传,可以告诉我如何吗?

谢谢

贾斯汀

4

2 回答 2

3

这是一种方法,您可以这样做以得到您想要的任何尺寸(不一定保持比例,这是一个优点和一个缺点):

UIImage *UIImageResize(UIImage *image, CGSize targetSize)
{
    UIGraphicsBeginImageContext(targetSize);
    CGContextRef bitmapContext = UIGraphicsGetCurrentContext();

    CGContextScaleCTM(bitmapContext, 1, -1);
    CGContextDrawImage(bitmapContext, (CGRect) { .origin.y = -targetSize.height, .size = targetSize }, image.CGImage);

    UIImage *results = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return results;
}

示例用法:

UIImage *resizedImage = UIImageResize([UIImage imageNamed:@"NukeBusters.png"], CGSizeMake(125, 130));
imageView.image = resizedImage;
于 2012-06-20T15:37:35.517 回答
2
UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:scale orientation:original.imageOrientation];

如果您想要图像的预定义尺寸,只需自己计算比例即可。

例如,如果你想限制宽度然后做

scale = desiredWidth / imageWidth

如果你想同时限制两者

scale1 = desiredWidth / imageWidth
scale2 = desiredHeight / imageHeight
scale = min (scale1 , scale2 )
于 2012-06-20T15:27:51.290 回答