- Generate pictures based on color
- Binary compression
code
import Foundation
import UIKit
extension UIImage {
/// generate images based on color
/// - Parameters:
/// -color: color
/ / / - width: the width
/ / / - height: high
/// - Returns: images
class func imageFromeColor(color: UIColor.width: CGFloat.height: CGFloat) - >UIImage{
let rect = CGRect.init(x: 0.0, y: 0.0, width: width, height: height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext(a)UIGraphicsEndImageContext(a)return image!
}
/// generate images based on color
/// - Parameters:
/// -color: color
/// -viewsize: size
/// - Returns: images
class func imageFromColor(color: UIColor.viewSize: CGSize) - >UIImage{
let rect: CGRect = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height)
UIGraphicsBeginImageContext(rect.size)
let context: CGContext = UIGraphicsGetCurrentContext(a)!
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext(a)UIGraphicsGetCurrentContext(a)return image!
}
/// binary compression
/// -parameter maxLength: specifies the maximum value of the Parameter.
/// - Returns: compressed image
func compressImageMid(maxLength: Int) -> UIImage? {
var compression: CGFloat = 1
guard var data = self.jpegData(compressionQuality: 1) else { return nil }
print("Before compression KB:\( Double((data.count)/1024))")
if data.count < maxLength {
return self
}
print("Pre-compression KB", data.count / 1024."KB")
var max: CGFloat = 1
var min: CGFloat = 0
for _ in 0..<6 {
compression = (max + min) / 2
data = self.jpegData(compressionQuality: compression)!
if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
min = compression
} else if data.count > maxLength {
max = compression
} else {
break}}print("Compressed KB", data.count / 1024."KB")
let resultImage: UIImage = UIImage(data: data)!
return resultImage
}
}
Copy the code
Demo: Github