我正在调整和压缩我的照片是一个不寻常的结果。
当我从相册中选择图像时,图像会压缩并调整大小。但是,如果我在从相机传递的图像上进行此操作,则图像变得奇怪地小(并且不可观看)。我作为测试所做的是在我的按钮中分配一些压缩和调整大小功能,该功能从相机源或相册中获取图像。以下是我的代码和控制台输出
@IBAction func testBtnPressed(sender: AnyObject) {
let img = selectedImageView.image!
print("before resize image \(img.dataLengh_kb)kb size \(img.size)")
let resizedImg = img.resizeWithWidth(1080)
print("1080 After resize image \(resizedImg!.dataLengh_kb)kb size \(resizedImg!.size)")
let compressedImageData = resizedImg!.mediumQualityJPEGNSData
print("Compress to medium quality = \(compressedImageData.length / 1024)kb")
}
extension UIImage {
var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! }
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
}
}
从相册中选择照片时
调整大小5004kb(3024.0,3024.0)之前
1080调整大小1023kb(1080.0,1080.0)后的图像
压缩到中等质量= 119kb
通过相机传递照片时
调整尺寸为4653kb(24385.536,24385.536)之前
1080调整大小后的图像大小为25kb(1080.576,1080.576)
压缩到中等质量= 4kb
答案 0 :(得分:0)
我已经用以下方法替换了图像大小调整功能,并且效果更好
func resizeImage(newHeight: CGFloat) -> UIImage {
let scale = newHeight / self.size.height
let newWidth = self.size.width * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
self.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}