如何在上传到服务器之前在 iOS 上压缩/调整图像大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4394491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compress/resize image on iOS before uploading to a server?
提问by joshholat
I'm currently uploading an image to a server using Imgur on iOS with the following code:
我目前正在使用以下代码在 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"];
The code works fine when run in the simulator and uploading a file from the simulator's photo library because I'm on a fast ethernet connection. However, the same code times out on the iPhone when selecting an image taken with the iPhone. So, I tried it by saving a small image from the web and attempting to upload that, which worked.
当在模拟器中运行并从模拟器的照片库上传文件时,代码运行良好,因为我使用的是快速以太网连接。但是,在选择用 iPhone 拍摄的图像时,相同的代码在 iPhone 上超时。所以,我通过从网上保存一个小图像并尝试上传来尝试它,这奏效了。
This leads me to believe the large images taken by the iPhone are timing out over the somewhat slow 3G network. Is there any way to compress/resize the image from the iPhone before sending it?
这让我相信 iPhone 拍摄的大图像在速度稍慢的 3G 网络上会超时。有没有办法在发送之前从 iPhone 压缩/调整图像大小?
采纳答案by TerryH
You should be able to make a smaller image by doing something like
您应该能够通过执行以下操作来制作较小的图像
UIImage *small = [UIImage imageWithCGImage:original.CGImage scale:0.25 orientation:original.imageOrientation];
(for a quarter-size image) then convert the smaller image to a PNG or whatever format you need.
(对于四分之一大小的图像)然后将较小的图像转换为 PNG 或您需要的任何格式。
回答by Tuan Nguyen
This snippet will resize the image:
此代码段将调整图像大小:
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
The variable newSize
is a CGSize
and can be defined like so:
变量newSize
是 aCGSize
并且可以像这样定义:
CGSize newSize = CGSizeMake(100.0f, 100.0f);
回答by Zorayr
A self-contained solution:
一个独立的解决方案:
- (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;
}
Thanks to @Tuan Nguyen.
感谢@Tuan Nguyen。
回答by nembleton
To complement @Tuan Nguyen, this is maybe the fastest and most elegant way to do that.
为了补充@Tuan Nguyen,这可能是最快、最优雅的方式。
To link to John Muchow's post at iphonedevelopertips.com, adding a category to a UIImage is a very very handy way to scale in a very fast fashion. Just calling
要链接到iphonedevelopertips.com 上 John Muchow 的帖子,向 UIImage 添加类别是一种非常方便的快速缩放方式。只是打电话
UIImage *_image = [[[UIImage alloc] initWithData:SOME_NSDATA] scaleToSize:CGSizeMake(640.0,480.0)];
returns you a 640x480 representation image of your NSDATA ( that could be an online image ) without any more line of code.
返回您的 NSDATA 的 640x480 表示图像(可能是在线图像),而无需更多代码行。
回答by Matthew Frederick
Matt Gemmell's MGImageUtilitiesare very nice, resizing efficiently and with some effort-reducing methods.
Matt Gemmell 的MGImageUtilities非常好,可以有效地调整大小并使用一些减少工作量的方法。
回答by Jagandeep Singh
In this code 0.5 means 50% ...
在这段代码中 0.5 意味着 50% ...
UIImage *original = image;
UIImage *compressedImage = UIImageJPEGRepresentation(original, 0.5f);
回答by Jagandeep Singh
use this simple method NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
使用这个简单的方法 NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
回答by PJeremyMalouf
Swift implementation of Zorayr's function (with a bit of a change to include height or width constraints by actual units not scale):
Zorayr 函数的 Swift 实现(有一点变化,包括由实际单位而不是比例的高度或宽度约束):
class func compressForUpload(original:UIImage, withHeightLimit heightLimit:CGFloat, andWidthLimit widthLimit:CGFloat)->UIImage{
let originalSize = original.size
var newSize = originalSize
if originalSize.width > widthLimit && originalSize.width > originalSize.height {
newSize.width = widthLimit
newSize.height = originalSize.height*(widthLimit/originalSize.width)
}else if originalSize.height > heightLimit && originalSize.height > originalSize.width {
newSize.height = heightLimit
newSize.width = originalSize.width*(heightLimit/originalSize.height)
}
// Scale the original image to match the new size.
UIGraphicsBeginImageContext(newSize)
original.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let compressedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return compressedImage
}
回答by Vineet Ravi
#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
+ (UIImage *)resizeImage:(UIImage *)image toResolution:(int)resolution {
NSData *imageData = UIImagePNGRepresentation(image);
CGImageSourceRef src = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
CFDictionaryRef options = (__bridge CFDictionaryRef) @{
(id) kCGImageSourceCreateThumbnailWithTransform : @YES,
(id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
(id) kCGImageSourceThumbnailMaxPixelSize : @(resolution)
};
CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
CFRelease(src);
UIImage *img = [[UIImage alloc]initWithCGImage:thumbnail];
return img;
}
回答by CodeOverRide
Swift 2.0 version of Jagandeep Singh method but need to convert data to image because NSData? is not converted UIImage automatically.
Swift 2.0 版本的 Jagandeep Singh 方法但需要将数据转换为图像,因为 NSData?不会自动转换 UIImage。
let orginalImage:UIImage = image
let compressedData = UIImageJPEGRepresentation(orginalImage, 0.5)
let compressedImage = UIImage(data: compressedData!)
回答by iOS Lifee
NsData *data=UiImageJPEGRepresentation(Img.image,0.2f);