-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCompress image unto 1 mb in swift
40 lines (38 loc) · 1.64 KB
/
Compress image unto 1 mb in swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
extension UIImageView{
func cacheImage(urlString: String){
if let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
{
image = nil
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
//imageView.startShimmering()
URLSession.shared.dataTask(with: url) {
data, response, error in
if error != nil
{
DispatchQueue.main.async {
//imageView.stopShimmering()
self.image = nil
}
}
if let _ = data {
DispatchQueue.main.async {
guard let imageToCache = UIImage(data: data!) else { return }
var compressionPercentage = 1.0
//if data is greater then 1mb then compress it and decrease size to 1 mb
if (data?.count ?? 0) > 1048576{
compressionPercentage = 1048576.0 / Double(data?.count ?? 1)
}
let compressedData = UIImageJPEGRepresentation(imageToCache, CGFloat(compressionPercentage))
guard let compressedimageToCache = UIImage(data: compressedData!) else { return }
imageCache.setObject(compressedimageToCache, forKey: urlString as AnyObject)
self.image = compressedimageToCache
//imageView.stopShimmering()
}
}
}.resume()
}
}
}