我一直在搜索谷歌,并且只遇到了降低高度/宽度的库或者通过CoreImage编辑UIImage外观的库。但我没有看到或找到一个图书馆,帖子解释了如何减少图像尺寸,所以当它上传时,它不是完整的图像尺寸。
到目前为止,我有这个: if image != nil {
//let data = NSData(data: UIImagePNGRepresentation(image))
let data = UIImagePNGRepresentation(image)
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"image\"; filename=\"randomName\"\r\n")
body.appendString("Content-Type: image/png\r\n\r\n")
body.appendData(data)
body.appendString("\r\n")
}
并且它发送了12MB照片。我怎样才能减少到1mb?谢谢!
答案 0 :(得分:145)
Xcode 8.2.1•Swift 3.0.2
extension UIImage {
func resized(withPercentage percentage: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage)
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
func resized(toWidth width: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
用法:
let myPicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
let myThumb1 = myPicture.resized(withPercentage: 0.1)
let myThumb2 = myPicture.resized(toWidth: 72.0)
答案 1 :(得分:64)
这是我调整图像大小的方法。
-(UIImage *)resizeImage:(UIImage *)image
{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = 300.0;
float maxWidth = 400.0;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.5;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth)
{
if(imgRatio < maxRatio)
{
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio)
{
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
使用此方法,我的6.5 MB图像缩小为104 KB。
Swift 4代码:
func resize(_ image: UIImage) -> UIImage {
var actualHeight = Float(image.size.height)
var actualWidth = Float(image.size.width)
let maxHeight: Float = 300.0
let maxWidth: Float = 400.0
var imgRatio: Float = actualWidth / actualHeight
let maxRatio: Float = maxWidth / maxHeight
let compressionQuality: Float = 0.5
//50 percent compression
if actualHeight > maxHeight || actualWidth > maxWidth {
if imgRatio < maxRatio {
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight
actualWidth = imgRatio * actualWidth
actualHeight = maxHeight
}
else if imgRatio > maxRatio {
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = maxWidth
}
else {
actualHeight = maxHeight
actualWidth = maxWidth
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight))
UIGraphicsBeginImageContext(rect.size)
image.draw(in: rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
UIGraphicsEndImageContext()
return UIImage(data: imageData!) ?? UIImage()
}
答案 2 :(得分:25)
如果有人正在寻找调整大小图片小于1MB Swift 3和4 。
只需复制并粘贴此扩展程序:
extension UIImage {
func resized(withPercentage percentage: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage)
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
func resizedTo1MB() -> UIImage? {
guard let imageData = UIImagePNGRepresentation(self) else { return nil }
var resizingImage = self
var imageSizeKB = Double(imageData.count) / 1000.0 // ! Or devide for 1024 if you need KB but not kB
while imageSizeKB > 1000 { // ! Or use 1024 if you need KB but not kB
guard let resizedImage = resizingImage.resized(withPercentage: 0.9),
let imageData = UIImagePNGRepresentation(resizedImage)
else { return nil }
resizingImage = resizedImage
imageSizeKB = Double(imageData.count) / 1000.0 // ! Or devide for 1024 if you need KB but not kB
}
return resizingImage
}
}
使用:
let resizedImage = originalImage.resizedTo1MB()
修改强> 请注意它的阻止用户界面,如果您认为它适合您的情况,请转到后台主题。
答案 3 :(得分:13)
与Leo Answer相同,但对SWIFT 2.0的编辑很少
extension UIImage {
func resizeWithPercentage(percentage: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage)))
imageView.contentMode = .ScaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.renderInContext(context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
func resizeWithWidth(width: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
imageView.contentMode = .ScaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.renderInContext(context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
}
答案 4 :(得分:5)
这是user4261201的答案,但很快,我目前正在使用:
egen
答案 5 :(得分:2)
如果您要以NSData
格式上传图片,请使用:
NSData *imageData = UIImageJPEGRepresentation(yourImage, floatValue);
yourImage
是您的UIImage
。
floatvalue
是压缩值(0.0到1.0)
以上是将图片转换为JPEG
。
PNG
使用:UIImagePNGRepresentation
注意:上面的代码在Objective-C中。请检查如何在Swift中定义NSData。
答案 6 :(得分:1)
我对这里的解决方案不满意,这些解决方案基于给定的KB大小生成图像,因为大多数解决方案都使用.jpegData(compressionQuality: x)
。此方法不适用于大图像,因为即使将压缩质量设置为0.0,大图像也将保持较大,例如新型iPhone的纵向模式所产生的10 MB仍将高于1 MB,且CompressionQuality设置为0.0。
因此,我使用了@Leo Dabus的答案,并将其重写为一个Helper Struct,它可以在背景que中转换图像:
import UIKit
struct ImageResizer {
static func resize(image: UIImage, maxByte: Int, completion: @escaping (UIImage?) -> ()) {
DispatchQueue.global(qos: .userInitiated).async {
guard let currentImageSize = image.jpegData(compressionQuality: 1.0)?.count else { return completion(nil) }
var imageSize = currentImageSize
var percentage: CGFloat = 1.0
var generatedImage: UIImage? = image
let percantageDecrease: CGFloat = imageSize < 10000000 ? 0.1 : 0.3
while imageSize > maxByte && percentage > 0.01 {
let canvas = CGSize(width: image.size.width * percentage,
height: image.size.height * percentage)
let format = image.imageRendererFormat
format.opaque = true
generatedImage = UIGraphicsImageRenderer(size: canvas, format: format).image {
_ in image.draw(in: CGRect(origin: .zero, size: canvas))
}
guard let generatedImageSize = generatedImage?.jpegData(compressionQuality: 1.0)?.count else { return completion(nil) }
imageSize = generatedImageSize
percentage -= percantageDecrease
}
completion(generatedImage)
}
}
}
用法:
ImageResizer.resize(image: image, maxByte: 800000) { img in
guard let resizedImage = img else { return }
// Use resizedImage
}
}
答案 7 :(得分:0)
我在研究 Swift 中的图像压缩和导出时遇到了这个问题,并以此为起点更好地理解问题并得出更好的技术。
UIGraphicsBeginImageContext()、UIGraphicsGetImageFromCurrentImageContext()、UIGraphicsEndImageContext() 过程是一种较旧的技术,已被 UIGraphicsImageRenderer 取代,如 iron_john_bonney 和 leo-dabus 所使用。他们的例子是作为 UIImage 的扩展编写的,而我选择编写一个独立的函数。可以通过比较(查看 UIGraphicsImageRenderer 调用及其附近)来识别方法中所需的差异,并且可以轻松地将其移植回 UIImage 扩展。
我认为这里使用的压缩算法有改进的潜力,所以我采取了一种方法,首先将图像调整为具有给定的总像素数,然后通过调整 jpeg 压缩来压缩它以达到指定的最终文件大小。指定像素总数的目的是避免陷入图像纵横比问题。虽然我没有做过详尽的调查,但我怀疑将图像缩放到指定的总像素数会将最终的 jpeg 图像文件大小置于一般范围内,然后可以使用 jpeg 压缩来确保文件大小限制以可接受的图像质量实现,前提是初始像素数不太高。
当使用 UIGraphicsImageRenderer 时,CGRect 在 Apple 主机设备上以 逻辑 像素指定,这与输出 jpeg 中的实际像素不同。查找设备像素比率以了解这一点。为了获得设备像素比,我尝试从环境中提取它,但这些技术导致操场崩溃,所以我使用了一种效率较低的技术。
如果您将此代码粘贴到 Xcode playround 并在 Resources 文件夹中放置适当的 .jpg 文件,则输出文件将放置在 Playground 输出文件夹中(使用实时视图中的快速查看找到此位置)。< /p>
import UIKit
func compressUIImage(_ image: UIImage?, numPixels: Int, fileSizeLimitKB: Double, exportImage: Bool) -> Data {
var returnData: Data
if let origWidth = image?.size.width,
let origHeight = image?.size.height {
print("Original image size =", origWidth, "*", origHeight, "pixels")
let imgMult = min(sqrt(CGFloat(numPixels)/(origWidth * origHeight)), 1) // This multiplier scales the image to have the desired number of pixels
print("imageMultiplier =", imgMult)
let cgRect = CGRect(origin: .zero, size: CGSize(width: origWidth * imgMult, height: origHeight * imgMult)) // This is in *logical* pixels
let renderer = UIGraphicsImageRenderer(size: cgRect.size)
let img = renderer.image { ctx in
image?.draw(in: cgRect)
}
// Now get the device pixel ratio if needed...
var img_scale: CGFloat = 1
if exportImage {
img_scale = img.scale
}
print("Image scaling factor =", img_scale)
// ...and use to ensure *output* image has desired number of pixels
let cgRect_scaled = CGRect(origin: .zero, size: CGSize(width: origWidth * imgMult/img_scale, height: origHeight * imgMult/img_scale)) // This is in *logical* pixels
print("New image size (in logical pixels) =", cgRect_scaled.width, "*", cgRect_scaled.height, "pixels") // Due to device pixel ratios, can have fractional pixel dimensions
let renderer_scaled = UIGraphicsImageRenderer(size: cgRect_scaled.size)
let img_scaled = renderer_scaled.image { ctx in
image?.draw(in: cgRect_scaled)
}
var compQual = CGFloat(1.0)
returnData = img_scaled.jpegData(compressionQuality: 1.0)!
var imageSizeKB = Double(returnData.count) / 1000.0
print("compressionQuality =", compQual, "=> imageSizeKB =", imageSizeKB, "KB")
while imageSizeKB > fileSizeLimitKB {
compQual *= 0.9
returnData = img_scaled.jpegData(compressionQuality: compQual)!
imageSizeKB = Double(returnData.count) / 1000.0
print("compressionQuality =", compQual, "=> imageSizeKB =", imageSizeKB, "KB")
}
} else {
returnData = Data()
}
return returnData
}
let image_orig = UIImage(named: "input.jpg")
let image_comp_data = compressUIImage(image_orig, numPixels: Int(4e6), fileSizeLimitKB: 1300, exportImage: true)
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
let filename = getDocumentsDirectory().appendingPathComponent("output.jpg")
try? image_comp_data.write(to: filename)
来源包括 Jordan Morgan 和 Hacking with Swift。
答案 8 :(得分:0)
我认为这里的问题的核心是如何在将UIImage的数据可靠地缩小到一定大小之后再上传到服务器,而不只是缩小UIImage本身。
如果您不需要压缩到特定大小,则使用func jpegData(compressionQuality: CGFloat) -> Data?
效果很好。但是,在某些情况下,我发现能够压缩到特定的指定文件大小以下很有用。在这种情况下,jpegData
是不可靠的,并且以这种方式对图像进行迭代压缩会导致文件大小达到稳定水平(并且可能非常昂贵)。相反,我更喜欢像Leo's answer中那样减小UIImage本身的大小,然后转换为jpegData并迭代检查减小的大小是否低于我选择的值(在我设置的边距内)。我根据当前文件大小与所需文件大小的比率来调整压缩步长系数,以加快最昂贵的第一次迭代(因为此时文件大小最大)。
快捷键5
extension UIImage {
func resized(withPercentage percentage: CGFloat, isOpaque: Bool = true) -> UIImage? {
let canvas = CGSize(width: size.width * percentage, height: size.height * percentage)
let format = imageRendererFormat
format.opaque = isOpaque
return UIGraphicsImageRenderer(size: canvas, format: format).image {
_ in draw(in: CGRect(origin: .zero, size: canvas))
}
}
func compress(to kb: Int, allowedMargin: CGFloat = 0.2) -> Data {
guard kb > 10 else { return Data() } // Prevents user from compressing below a limit (10kb in this case).
let bytes = kb * 1024
var compression: CGFloat = 1.0
let step: CGFloat = 0.05
var holderImage = self
var complete = false
while(!complete) {
guard let data = holderImage.jpegData(compressionQuality: 1.0) else { break }
let ratio = data.count / bytes
if data.count < Int(CGFloat(bytes) * (1 + allowedMargin)) {
complete = true
return data
} else {
let multiplier:CGFloat = CGFloat((ratio / 5) + 1)
compression -= (step * multiplier)
}
guard let newImage = holderImage.resized(withPercentage: compression) else { break }
holderImage = newImage
}
return Data()
}
}
和用法:
let data = image.compress(to: 1000)
答案 9 :(得分:0)
df = pandas.DataFrame(data)
columns = df.columns
for i in columns:
if str(df[i][0]).startswith('{'):
print('True')
else:
print('False')
答案 10 :(得分:0)
当我尝试使用公认的答案来调整要在我的项目中使用的图像的大小时,它会变得非常像素化和模糊。我最终得到了这段代码来调整图像的大小,而又不增加像素化或模糊:
func scale(withPercentage percentage: CGFloat)-> UIImage? {
let cgSize = CGSize(width: size.width * percentage, height: size.height * percentage)
let hasAlpha = true
let scale: CGFloat = 0.0 // Use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(cgSize, !hasAlpha, scale)
self.draw(in: CGRect(origin: CGPoint.zero, size: cgSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
return scaledImage
}
答案 11 :(得分:0)
与Objective-C相同:
界面:
@interface UIImage (Resize)
- (UIImage *)resizedWithPercentage:(CGFloat)percentage;
- (UIImage *)resizeTo:(CGFloat)weight isPng:(BOOL)isPng jpegCompressionQuality:(CGFloat)compressionQuality;
@end
实现:
#import "UIImage+Resize.h"
@implementation UIImage (Resize)
- (UIImage *)resizedWithPercentage:(CGFloat)percentage {
CGSize canvasSize = CGSizeMake(self.size.width * percentage, self.size.height * percentage);
UIGraphicsBeginImageContextWithOptions(canvasSize, false, self.scale);
[self drawInRect:CGRectMake(0, 0, canvasSize.width, canvasSize.height)];
UIImage *sizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return sizedImage;
}
- (UIImage *)resizeTo:(CGFloat)weight isPng:(BOOL)isPng jpegCompressionQuality:(CGFloat)compressionQuality {
NSData *imageData = isPng ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, compressionQuality);
if (imageData && [imageData length] > 0) {
UIImage *resizingImage = self;
double imageSizeKB = [imageData length] / weight;
while (imageSizeKB > weight) {
UIImage *resizedImage = [resizingImage resizedWithPercentage:0.9];
imageData = isPng ? UIImagePNGRepresentation(resizedImage) : UIImageJPEGRepresentation(resizedImage, compressionQuality);
resizingImage = resizedImage;
imageSizeKB = (double)(imageData.length / weight);
}
return resizingImage;
}
return nil;
}
用法:
#import "UIImage+Resize.h"
UIImage *resizedImage = [self.picture resizeTo:2048 isPng:NO jpegCompressionQuality:1.0];
答案 12 :(得分:0)
Swift4.2
let imagedata = yourImage.jpegData(compressionQuality: 0.1)!
答案 13 :(得分:0)
我认为swift本身提供的最简单方法就是将图像压缩成压缩数据,下面是swift 4.2中的代码
let imageData = yourImageTobeCompressed.jpegData(compressionQuality: 0.5)
您可以发送此imageData上载到服务器。
答案 14 :(得分:0)
使用此功能,您可以控制所需的大小:
func jpegImage(image: UIImage, maxSize: Int, minSize: Int, times: Int) -> Data? {
var maxQuality: CGFloat = 1.0
var minQuality: CGFloat = 0.0
var bestData: Data?
for _ in 1...times {
let thisQuality = (maxQuality + minQuality) / 2
guard let data = image.jpegData(compressionQuality: thisQuality) else { return nil }
let thisSize = data.count
if thisSize > maxSize {
maxQuality = thisQuality
} else {
minQuality = thisQuality
bestData = data
if thisSize > minSize {
return bestData
}
}
}
return bestData
}
方法调用示例:
jpegImage(image: image, maxSize: 500000, minSize: 400000, times: 10)
它将尝试获取最大大小和最小大小之间的文件,但仅尝试次数。如果在这段时间内失败,它将返回nil。
答案 15 :(得分:0)
基于同福的答案。调整为特定的文件大小。像0.7 MB一样,您可以使用此代码。
extension UIImage {
func resize(withPercentage percentage: CGFloat) -> UIImage? {
var newRect = CGRect(origin: .zero, size: CGSize(width: size.width*percentage, height: size.height*percentage))
UIGraphicsBeginImageContextWithOptions(newRect.size, true, 1)
self.draw(in: newRect)
defer {UIGraphicsEndImageContext()}
return UIGraphicsGetImageFromCurrentImageContext()
}
func resizeTo(MB: Double) -> UIImage? {
guard let fileSize = self.pngData()?.count else {return nil}
let fileSizeInMB = CGFloat(fileSize)/(1024.0*1024.0)//form bytes to MB
let percentage = 1/fileSizeInMB
return resize(withPercentage: percentage)
}
}
答案 16 :(得分:0)
这是我在swift 3中为调整UIImage的大小而做的。它将图像大小减小到小于100kb。它按比例工作!
extension UIImage {
class func scaleImageWithDivisor(img: UIImage, divisor: CGFloat) -> UIImage {
let size = CGSize(width: img.size.width/divisor, height: img.size.height/divisor)
UIGraphicsBeginImageContext(size)
img.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
用法:
let scaledImage = UIImage.scaleImageWithDivisor(img: capturedImage!, divisor: 3)
答案 17 :(得分:-1)
使用.resizeToMaximumBytes
调整UIImage的大小