gpt4 book ai didi

ios - 使用大型 UIImage 数组时的内存问题导致崩溃(快速)

转载 作者:IT王子 更新时间:2023-10-29 05:49:04 24 4
gpt4 key购买 nike

在我的应用程序中,我有一个图像数组,其中包含我的相机拍摄的所有图像。我正在使用 collectionView 来显示这些图像。但是,当此图像阵列达到第 20 个左右图像时,它会崩溃。我认为这是由于内存问题造成的。我如何以内存高效的方式将图像存储在图像数组中?

Michael Dauterman 使用缩略图提供了答案。我希望除此之外还有解决方案。也许将图片存储到 NSData 或 CoreData 中?

相机.swift:

//What happens after the picture is chosen
func imagePickerController(picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject:AnyObject]){
//cast image as a string
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
self.dismissViewControllerAnimated(true, completion: nil)
//if the mediaType it actually is an image (jpeg)
if mediaType.isEqualToString(kUTTypeImage as NSString as String){
let image = info[UIImagePickerControllerOriginalImage] as! UIImage

//Our outlet for imageview
appraisalPic.image = image

//Picture taken, to be added to imageArray
globalPic = image

//image:didFinish.. if we arent able to save, pass to contextInfo in Error Handling
if (newMedia == true){
UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)

}
}
}

新记录.swift

var imageArray:[UIImage] = [UIImage]()
viewDidLoad(){

//OUR IMAGE ARRAY WHICH HOLDS OUR PHOTOS, CRASHES AROUND 20th PHOTO ADDED
imageArray.append(globalPic)

//Rest of NewRecord.swift is code which adds images from imageArray to be presented on a collection view
}

最佳答案

我在自己的应用程序中遇到过低内存问题,这些应用程序必须使用大量高分辨率的 UIImage 对象。

解决方案是在 imageArray 中保存图像的缩略图(占用更少的内存),然后显示它们。如果用户确实需要查看全分辨率图像,您可以让他们点击图像,然后重新加载并显示相机胶卷中的全尺寸 UIImage。

下面是一些允许您创建缩略图的代码:

// image here is your original image
let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(0.5, 0.5))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: size))

let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageArray.append(scaledImage)

more information about these techniques can be found in this NSHipster article .

swift 4 -

// image here is your original image
let size = image.size.applying(CGAffineTransform(scaleX: 0.5, y: 0.5))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.draw(in: CGRect(origin: .zero, size: size))

let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

关于ios - 使用大型 UIImage 数组时的内存问题导致崩溃(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31898326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com