Reputation: 375
I want to compress image using above lossless algorithms, but these algorithm works on data but not on image data. is there anyway to compress image using these algorithms here is a code
var org = UIImage(named: "Dragon.jpg")
var res: Data = UIImagePNGRepresentation(org!)!
print("Image before Compressing")
print(res.count)
print(res)
orignal.image = UIImage(data: res)
res = res.compress(withAlgorithm: .LZFSE)!
print("Image After Compressing")
print(res.count)
print(res)
res = res.decompress(withAlgorithm: .LZFSE)!
print("Image After Decompressing")
print(res)
print(res.count)
compress.image =
UIImage(data: res)
OutPut Image before Compressing
1915549
1915549 bytes
Image After Compressing
1935259
1935259 bytes
Image After Decompressing
1915549
1915549 bytes
Upvotes: 3
Views: 1022
Reputation: 815
Compress that data using this algorithm and from that data make image .
let image : UIImage = UIImage(data: imageData)
So U will get that image . Use This If You Want To Compress Image :- (Resolution changing)
func compressImage(image:UIImage) -> Data? {
var actualHeight : CGFloat = image.size.height
var actualWidth : CGFloat = image.size.width
let maxHeight : CGFloat = 2732 .0
let maxWidth : CGFloat = 2048.0
var imgRatio : CGFloat = actualWidth/actualHeight
let maxRatio : CGFloat = maxWidth/maxHeight
var compressionQuality : CGFloat = 0.5
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.0, y: 0.0, width: actualWidth, height: actualHeight)
UIGraphicsBeginImageContext(rect.size)
image.draw(in: rect)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
guard let imageData = UIImageJPEGRepresentation(img, compressionQuality)else{
return nil
}
return imageData
}
Upvotes: 1