如何在iOS上传到服务器之前压缩/调整图像大小?

76

我目前正在使用以下代码,在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"];

当我在模拟器中运行代码并从模拟器的照片库上传文件时,代码可以正常工作,因为我所在的以太网连接速度很快。然而,当我在iPhone上选择一个拍摄的图像时,同样的代码会超时。因此,我尝试保存从网络上获取的小图片并尝试上传,这是成功的。

这导致我相信,由于有些缓慢的3G网络,iPhone拍摄的大型图像会超时。是否有办法在发送之前从iPhone压缩/调整图片大小?

13个回答

0

这是 Jagandeep Singh 方法的 Swift 2.0 版本,但需要将数据转换为图像,因为 NSData 不会自动转换为 UIImage。

let orginalImage:UIImage = image

let compressedData = UIImageJPEGRepresentation(orginalImage, 0.5)
let compressedImage = UIImage(data: compressedData!)

-1
-(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
{
CGFloat actualHeight = orginalImage.size.height;
CGFloat actualWidth = orginalImage.size.width;
//  if(actualWidth <= size.width && actualHeight<=size.height)
//  {
//      return orginalImage;
//  }
float oldRatio = actualWidth/actualHeight;
float newRatio = size.width/size.height;
if(oldRatio < newRatio)
{
    oldRatio = size.height/actualHeight;
    actualWidth = oldRatio * actualWidth;
    actualHeight = size.height;
}
else
{
    oldRatio = size.width/actualWidth;
    actualHeight = oldRatio * actualHeight;
    actualWidth = size.width;
}

CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
UIGraphicsBeginImageContext(rect.size);
[orginalImage drawInRect:rect];
orginalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return orginalImage;
 }

这是方法调用

 UIImage *compimage=[appdel resizeImage:imagemain resizeSize:CGSizeMake(40,40)];      

它返回图像,您可以在任何地方显示此图像...........


-36

你应该能够通过类似以下的方式来制作一个较小的图像

UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:0.25 orientation:original.imageOrientation];

(对于四分之一大小的图像)然后将较小的图像转换为PNG或您需要的任何格式。

52
这会改变所报告的缩放后图片的大小,但实际上不会改变图片数据。原始图片和缩放后图片所生成的NSData数据长度几乎相同。 - Joshua Sullivan
13
这行不通!这不应该是被接受的答案!我在我的应用程序中实现了它,只发现压缩到原始图像大小的25%的图像仍具有与原始图像相同的字节大小。我不知道为什么会有这么多人赞同这个不能工作的答案! - Michael
不起作用。缩放图像,但保留数据的原始大小。 - nont
再试一次,还是不行。请删除/更新此答案,以免浪费更多时间。 - Zorayr
它不会改变文件大小,因为UIImage的深拷贝是CGImage,而调整大小并不会改变图像。请参阅苹果文档,要更改文件大小,您需要创建一个缩放版本的新图像。了解指针是什么。还应该知道,缩小然后放大会导致图像丢失,如果您将其用于任何重要事项,它以后看起来会模糊不清。压缩它并使用JPegCompress或其他函数名称发送它。 - Nick Turner
@FahimParkar +38 -70 哈哈 - Ver Nick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接