-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathMLKitExtensions.swift
36 lines (29 loc) · 1.11 KB
/
MLKitExtensions.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
import CoreGraphics
import UIKit
// MARK: - UIImage
extension UIImage {
/// Creates and returns a new image scaled to the given size. The image preserves its original PNG
/// or JPEG bitmap info.
///
/// - Parameter size: The size to scale the image to.
/// - Returns: The scaled image or `nil` if image could not be resized.
public func scaledImage(with size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()?.data.flatMap(UIImage.init)
}
// MARK: - Private
/// The PNG or JPEG data representation of the image or `nil` if the conversion failed.
private var data: Data? {
#if swift(>=4.2)
return self.pngData() ?? self.jpegData(compressionQuality: Constant.jpegCompressionQuality)
#else
return self.pngData() ?? self.jpegData(compressionQuality: Constant.jpegCompressionQuality)
#endif // swift(>=4.2)
}
}
// MARK: - Constants
private enum Constant {
static let jpegCompressionQuality: CGFloat = 0.8
}