Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func resizeImageOriginalSize(target: CGSize) -> UIImage? {
- let image = self
- var num = self.getFileSize()
- var newImager = UIImage()
- var targetSize = target
- var index = 0
- DispatchQueue.main.async {
- NotificationCenter.default.post(
- name: .updateProgress,
- object: self,
- userInfo: ["Preparing to convert file.": 0.0])
- }
- let incre = num / 500
- var percent = 0.0
- let orig = num
- while num > 500 {
- index = index + 1
- var actualHeight: Float = Float(image.size.height)
- var actualWidth: Float = Float(image.size.width)
- let maxHeight: Float = Float(targetSize.height)
- let maxWidth: Float = Float(targetSize.width)
- var imgRatio: Float = actualWidth / actualHeight
- let maxRatio: Float = maxWidth / maxHeight
- var 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
- compressionQuality = 1.0
- }
- }
- let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight))
- UIGraphicsBeginImageContextWithOptions(rect.size, false, CGFloat(compressionQuality))
- image.draw(in: rect)
- let newImage = UIGraphicsGetImageFromCurrentImageContext()
- UIGraphicsEndImageContext()
- num = newImage!.getFileSize()
- newImager = newImage!
- print(num)
- var w = targetSize.width - 1
- var h = targetSize.height - 1
- if index == 10 {
- let diff = orig - num
- let incree = diff / 10
- let needed = 500 / incree
- w = CGFloat(needed)
- h = CGFloat(needed)
- }
- targetSize = CGSize(width: w, height: h)
- percent = Double(percent) + Double(incre)
- DispatchQueue.main.async {
- NotificationCenter.default.post(
- name: .updateProgress,
- object: self,
- userInfo: ["CONVERT": percent])
- }
- }
- return newImager
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement