Created
August 23, 2016 06:05
-
-
Save hprobotic/3ec4bb30a1fdf32dd8f7d077cbc77e97 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
// | |
// UIImageExtension.swift | |
// PicPic | |
// | |
// Created by Johnny Pham on 6/28/16. | |
// Copyright © 2016 John Pham. All rights reserved. | |
// | |
import UIKit | |
extension UIImage { | |
var uncompressedPNGData: NSData { return UIImagePNGRepresentation(self)! } | |
var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! } | |
var highQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.75)! } | |
var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! } | |
var lowQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.25)! } | |
var lowestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.0)! } | |
func compressImage() -> NSData { | |
// Reducing file size to a 10th | |
let image = self as UIImage | |
var actualHeight: CGFloat = image.size.height | |
var actualWidth: CGFloat = image.size.width | |
let maxHeight: CGFloat = IMAGE_MAX_HEIGHT | |
let maxWidth: CGFloat = IMAGE_MAX_WIDTH | |
var imgRatio: CGFloat = actualWidth/actualHeight | |
let maxRatio: CGFloat = maxWidth/maxHeight | |
let compressionQuality: CGFloat = IMAGE_COMPRESSION_QUALITY | |
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 = CGRectMake(0.0, 0.0, actualWidth, 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