Created
May 11, 2016 17:30
-
-
Save benaneesh/b05e27c88ca86914a75114abf8775c0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func compressImage(image:UIImage) -> NSData? { | |
| var actualHeight : CGFloat = image.size.height | |
| var actualWidth : CGFloat = image.size.width | |
| let maxHeight : CGFloat = 1136.0 | |
| let maxWidth : CGFloat = 640.0 | |
| var imgRatio : CGFloat = actualWidth/actualHeight | |
| let maxRatio : CGFloat = maxWidth/maxHeight | |
| var compressionQuality : CGFloat = 0.3 | |
| 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 | |
| } | |
| } | |
| let rect = CGRect(x: 0, y: 0, width: actualWidth, height: actualHeight) | |
| UIGraphicsBeginImageContext(rect.size); | |
| image.drawInRect(rect) | |
| let img = UIGraphicsGetImageFromCurrentImageContext() | |
| let imageData = UIImageJPEGRepresentation(img, compressionQuality) | |
| UIGraphicsEndImageContext() | |
| return imageData | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment