Files
suixinkan_uikit/suixinkan/Core/WeChat/WeChatThumbImageProcessor.swift

70 lines
2.5 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// WeChatThumbImageProcessor.swift
// suixinkan
//
import UIKit
/// 32KB
enum WeChatThumbImageProcessor {
///
static let maxThumbBytes = 32 * 1024
///
static let maxMiniProgramHDImageBytes = 128 * 1024
///
static func makeThumbData(from image: UIImage, maxBytes: Int = maxThumbBytes) -> Data? {
guard maxBytes > 0 else { return nil }
let resized = resize(image, maxPixel: 120)
var quality: CGFloat = 0.82
var data = resized.jpegData(compressionQuality: quality)
while let current = data, current.count > maxBytes, quality > 0.12 {
quality -= 0.1
data = resized.jpegData(compressionQuality: quality)
}
guard let result = data, result.count <= maxBytes else { return nil }
return result
}
///
static func makeMiniProgramHDImageData(
from image: UIImage,
maxBytes: Int = maxMiniProgramHDImageBytes
) -> Data? {
guard maxBytes > 0 else { return nil }
let resized = resize(image, maxPixel: 500)
var quality: CGFloat = 0.86
var data = resized.jpegData(compressionQuality: quality)
while let current = data, current.count > maxBytes, quality > 0.12 {
quality -= 0.08
data = resized.jpegData(compressionQuality: quality)
}
guard let result = data, result.count <= maxBytes else { return nil }
return result
}
/// 使
static func resize(_ image: UIImage, maxPixel: CGFloat) -> UIImage {
let sourceSize = image.size
guard sourceSize.width > 0, sourceSize.height > 0 else { return image }
let maxSide = max(sourceSize.width, sourceSize.height)
guard maxSide > maxPixel else { return image }
let scale = maxPixel / maxSide
let targetSize = CGSize(width: sourceSize.width * scale, height: sourceSize.height * scale)
let format = UIGraphicsImageRendererFormat.default()
format.scale = 1
let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
return renderer.image { _ in
image.draw(in: CGRect(origin: .zero, size: targetSize))
}
}
}