[英]Photo resizing and compressing
I am resizing and compressing my photos an unusual result. 我正在调整大小和压缩照片,结果不正常。
When I choose the image from photo album, the image compresses and resizes fine. 当我从相册中选择图像时,图像会压缩并调整大小。 However, If I do it on a image that was passed from the camera, the image becomes oddly small (And unwatchable). 但是,如果我在从相机传来的图像上进行拍摄,则图像会变得异常小(并且无法观看)。 What I have done as a test is assign some compression and resizing function in my button that takes an image either from a camera source or photo album. 作为测试,我在按钮中分配了一些压缩和调整大小功能,以从相机源或相册中获取图像。 Below are my code and console output 以下是我的代码和控制台输出
@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
}
}
When photo was selected from photo album 从相册中选择照片时
before resize image 5004kb size (3024.0, 3024.0) 调整大小之前的图像5004kb大小(3024.0,3024.0)
1080 After resize image 1023kb size (1080.0, 1080.0) 1080调整大小后的图片1023kb大小(1080.0,1080.0)
Compress to medium quality = 119kb 压缩到中等质量= 119kb
When photo was passed by camera 相机通过照片时
before resize image 4653kb size (24385.536, 24385.536) 调整大小之前的图像4653kb大小(24385.536,24385.536)
1080 After resize image 25kb size (1080.576, 1080.576) 1080调整大小后的图片25kb大小(1080.576,1080.576)
Compress to medium quality = 4kb 压缩到中等质量= 4kb
I have replaced the image resizing function with the following one and it worked a lot better 我已经用以下代码替换了图像大小调整功能,并且效果更好
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.