UIImage是一个很常见的组件，最常见的就是通过name或者路径读取。

## 两种创建方式的解释

public init?(named name: String)

This method checks the system caches for an image object with the specified name and returns the variant of that image that is best suited for the main screen. If a matching image object is not already in the cache, this method creates the image from an available asset catalog or loads it from disk. The system may purge cached image data at any time to free up memory. Purging occurs only for images that are in the cache but are not currently being used.

public init?(contentsOfFile path: String)

This method loads the image data into memory and marks it as purgeable. If the data is purged and needs to be reloaded, the image object loads that data again from the specified path.

## 图片解码区别

DispatchQueue.global().async {
let coverImage = UIImage(contentsOfFile: path)
DispatchQueue.main.async {
imageView.image = coverImage
}
}

imageNamed方法会在加载图片之后立刻进行解码，所以如果上面代码中的coverImage是通过imageNamed创建的话就可以提升了解码加载。问题在于imageNamed只对从应用资源束中的图片有效，所以对用户生成的图片内容或者是下载的图片就没法使用了。

## 优化

DispatchQueue.global().async {
let imageURL = URL(fileURLWithPath: path) as CFURL
let options = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: 500
] as CFDictionary

if let source: CGImageSource = CGImageSourceCreateWithURL(imageURL, nil),
let imageRef: CGImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options) {
self.mCoverImage = UIImage(cgImage: imageRef)
}
DispatchQueue.main.async {
imageView.image = self.mCoverImage
}
}

## 效果对比

Image IOimageWithContentsOfFile

## 参考文章

☟☟可点击下方广告支持一下☟☟

Last modification：August 14, 2022