我编写了一个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);
在提交此图片之前,我想调整大小以使其更容易,更快速上传,可以向我展示如何吗?
由于
贾斯汀
答案 0 :(得分: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;
答案 1 :(得分: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 )