3 回答
TA贡献1877条经验 获得超1个赞
是的,你可以使用UIImageJPEGRepresentation,而不是UIImagePNGRepresentation减少图像文件的大小。您可以按照以下方式创建扩展UIImage:
Xcode 8.2•Swift 3.0.2
extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ quality: JPEGQuality) -> Data? {
return UIImageJPEGRepresentation(self, quality.rawValue)
}
}
编辑/更新:
Xcode 10 Swift 4.2
extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ jpegQuality: JPEGQuality) -> Data? {
return jpegData(compressionQuality: jpegQuality.rawValue)
}
}
用法:
if let imageData = image.jpeg(.lowest) {
print(imageData.count)
}
TA贡献1871条经验 获得超13个赞
如果要将图像大小限制为某个具体值,可以执行以下操作:
import UIKit
extension UIImage {
// MARK: - UIImage+Resize
func compressTo(_ expectedSizeInMb:Int) -> UIImage? {
let sizeInBytes = expectedSizeInMb * 1024 * 1024
var needCompress:Bool = true
var imgData:Data?
var compressingValue:CGFloat = 1.0
while (needCompress && compressingValue > 0.0) {
if let data:Data = UIImageJPEGRepresentation(self, compressingValue) {
if data.count < sizeInBytes {
needCompress = false
imgData = data
} else {
compressingValue -= 0.1
}
}
}
if let data = imgData {
if (data.count < sizeInBytes) {
return UIImage(data: data)
}
}
return nil
}
}
TA贡献1784条经验 获得超9个赞
Jus Fixing for Xcode 7,于09/21/2015测试,工作正常:
只需创建一个扩展UIImage,如下所示:
extension UIImage
{
var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! }
var highQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.75)!}
var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! }
var lowQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.25)!}
var lowestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.0)! }
}
然后,您可以像这样使用它:
let imageData = imagePassed.lowestQualityJPEGNSData
- 3 回答
- 0 关注
- 611 浏览
添加回答
举报