let url =URL(string: "http://pic.pptbz.com/201506/2015070581208537.JPG")! let session =URLSession.shared let task = session.dataTask(with: url) {(data, resp, error) in let data = data! let image =UIImage(data: data)! print(data) print(image) } task.resume()
let url =URL(string: "http://pic.pptbz.com/201506/2015070581208537.JPG")! let session =URLSession.shared let task = session.dataTask(with: url) {(data, resp, error) in let data = data! let image =UIImage(data: data)! DispatchQueue.main.async { imageView.image = image } } task.resume()
let bundle =Bundle.main let jpg = bundle.url(forResource: "1", withExtension: "JPG") let data =try!Data(contentsOf: jpg!) let image =UIImage(data: data) print(data) print(image)
let url =URL(string: "http://pic31.nipic.com/20130702/13133954_121018329102_2.png")! let session =URLSession.shared let task = session.dataTask(with: url) { (data, resp, error) in let data = data! let image =UIImage(data: data)! print(data) print(image) DispatchQueue.main.async { self.imageView.image = image } } task.resume()
打印结果为:
1 2
78144 bytes <UIImage: 0x1017eaa70>, {1024, 576}
内存占用提升约 2.3 MB, 符合预期.
下面就来介绍收集到的一些比较有效的减少 PNG 图片加载时内存占用的办法.
调整尺寸后重绘
这种方法的特点就是简单, 但属于 CPU 消耗型的操作, 在多张图片都需要这样的操作时就显得很不适用了.
如下是代码:
1 2 3 4 5 6 7 8
privatefuncresizeAndRedrawImageWith(image: UIImage, newSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, 0) let rect =CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) image.draw(in: rect) let newImage =UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! }