jos*_*lat 75 file-upload uiimage nsdata ios4 ios
我目前正在iOS上使用Imgur将图像上传到服务器,代码如下:
NSData* imageData = UIImagePNGRepresentation(image);
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* fullPathToFile = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"SBTempImage.png"];
[imageData writeToFile:fullPathToFile atomically:NO];
[uploadRequest setFile:fullPathToFile forKey:@"image"];
Run Code Online (Sandbox Code Playgroud)
代码在模拟器中运行并从模拟器的照片库上传文件时工作正常,因为我在快速以太网连接上.但是,在选择使用iPhone拍摄的图像时,相同的代码会在iPhone上超时.所以,我尝试通过从网络上保存一个小图像并试图上传它,这是有效的.
这让我相信iPhone拍摄的大图像会在有点慢的3G网络上超时.有没有办法在发送之前压缩/调整iPhone的图像大小?
谢谢!
Tua*_*yen 201
此代码段将调整图片大小:
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)
变量newSize是a CGSize,可以这样定义:
CGSize newSize = CGSizeMake(100.0f, 100.0f);
Run Code Online (Sandbox Code Playgroud)
Zor*_*ayr 38
一个独立的解决方案:
- (UIImage *)compressForUpload:(UIImage *)original scale:(CGFloat)scale
{
// Calculate new size given scale factor.
CGSize originalSize = original.size;
CGSize newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale);
// Scale the original image to match the new size.
UIGraphicsBeginImageContext(newSize);
[original drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *compressedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return compressedImage;
}
Run Code Online (Sandbox Code Playgroud)
感谢@Tuan Nguyen.
nem*_*ton 16
为了补充@Tuan Nguyen,这可能是最快,最优雅的方式.
要链接到John Muchow在iphonedevelopertips.com上的帖子,在UIImage中添加一个类别是一种非常方便的扩展方式.只是打电话
UIImage *_image = [[[UIImage alloc] initWithData:SOME_NSDATA] scaleToSize:CGSizeMake(640.0,480.0)];
Run Code Online (Sandbox Code Playgroud)
返回你的NSDATA(可能是一个在线图像)的640x480表示图像,没有任何更多的代码行.
小智 6
在此代码中,0.5表示50%......
UIImage *original = image;
UIImage *compressedImage = UIImageJPEGRepresentation(original, 0.5f);
Run Code Online (Sandbox Code Playgroud)
小智 -36
您应该能够通过执行类似的操作来制作较小的图像
UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:0.25 orientation:original.imageOrientation];
Run Code Online (Sandbox Code Playgroud)
(对于四分之一大小的图像)然后将较小的图像转换为 PNG 或您需要的任何格式。
| 归档时间: |
|
| 查看次数: |
96885 次 |
| 最近记录: |