UIImage+CNLiveColorImage.swift
1.88 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
//
// UIImage+CNLiveColorImage.swift
// metaCode
//
// Created by open on 2023/6/20.
//
import Foundation
extension UIImage {
/// 生成纯色图片
/// - Parameters:
/// - color: 颜色
/// - size: 大小
/// - Returns: 返回image
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
/// 图片进行压缩
/// - Returns: 返回data
func imageWithZip() -> Data {
var image_data = jpegData(compressionQuality: 1.0)!
if image_data.count > 19*1024*1024 {//19M以上
let dataLength = NSNumber(integerLiteral: image_data.count)
let limitLenght = NSNumber(integerLiteral: 19*1024*1024)
var scale = limitLenght.floatValue / dataLength.floatValue
scale = scale > 0.3 ? 0.3 : scale
image_data = jpegData(compressionQuality: CGFloat(scale))!
} else if image_data.count > 10*1024*1024 {//10M<x<=19M
image_data = jpegData(compressionQuality: 0.3)!
} else if image_data.count > 1*1024*1024 {//1M<x<=10M
image_data = jpegData(compressionQuality: 0.7)!
} else if image_data.count > 512*1024 {//0.5M<x<1M
image_data = jpegData(compressionQuality: 0.8)!
} else if image_data.count > 256*1024 {//0.25M-0.5M
image_data = jpegData(compressionQuality: 0.9)!
} else {
//不压缩
}
print("压缩图片输出大小:\(CGFloat(image_data.count)/1024.0)kb")
return image_data
}
}