Compress an image with fixed width iOS swift
Solution:
The below code will return the Data with compressed image.You can give the image and the width of the image.
func compressImage(img:UIImage,givenWidth:CGFloat) ->Data {
print("before compression",UIImagePNGRepresentation(img)?.count)
print("before width and height",img.size)
let newWidth:CGFloat = givenWidth
let scale = newWidth / img.size.width
let newHeight = img.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
img.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var compression = 0.9
let maxCompression = 0.1
print("after compression",UIImagePNGRepresentation(newImage!)?.count)
print("after width and height",newImage?.size)
var imageData = UIImageJPEGRepresentation(newImage!, CGFloat(compression));
while ((imageData?.count)! > maxImgSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(newImage!, CGFloat(compression))
}
return imageData!
}
The below code will return the Data with compressed image.You can give the image and the width of the image.
func compressImage(img:UIImage,givenWidth:CGFloat) ->Data {
print("before compression",UIImagePNGRepresentation(img)?.count)
print("before width and height",img.size)
let newWidth:CGFloat = givenWidth
let scale = newWidth / img.size.width
let newHeight = img.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
img.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var compression = 0.9
let maxCompression = 0.1
print("after compression",UIImagePNGRepresentation(newImage!)?.count)
print("after width and height",newImage?.size)
var imageData = UIImageJPEGRepresentation(newImage!, CGFloat(compression));
while ((imageData?.count)! > maxImgSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(newImage!, CGFloat(compression))
}
return imageData!
}
Comments
Post a Comment