我正在尝试在我的 ios 应用程序中实现共享扩展。我想分享照片,在应用程序将它们发送到后端之前我想调整照片的大小。 我正在使用这个功能:
+(UIImage*) resizedImage :(UIImage*) image andPreferredSize:(CGSize) size
{
if(image.size.height > size.height && image.size.width > size.width)
{
float ratio1 = image.size.height/size.height;
float ratio2 = image.size.width/size.width;
float ratio3 = ratio1 < ratio2 ? ratio1 : ratio2;
CGSize newSize = CGSizeMake(image.size.width/ratio3 , image.size.height/ratio3);
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
image = [[newImage retain] autorelease];
UIGraphicsEndImageContext();
}
return image;
}
如果我在第二张照片中共享多张照片(在串行队列中),我会收到此消息错误并崩溃:
Message from debugger: Terminated due to memory issue
内存使用量不超过20 Mb。知道可能是什么问题吗?
这是我用来调整图像大小的代码。您很快就可以从中找到线索。
func resize(targetSize: CGSize) -> Data {
var actualHeight = Float(self.size.height)
var actualWidth = Float(self.size.width)
let maxHeight: Float = Float(targetSize.width)
let maxWidth: Float = Float(targetSize.height)
var imgRatio: Float = actualWidth / actualHeight
let maxRatio: Float = maxWidth / maxHeight
let compressionQuality: Float = 0.5
//50 percent compression
if actualHeight > maxHeight || actualWidth > maxWidth {
if imgRatio < maxRatio {
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight
actualWidth = imgRatio * actualWidth
actualHeight = maxHeight
}
else if imgRatio > maxRatio {
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth
actualHeight = imgRatio * actualHeight
actualWidth = maxWidth
}
else {
actualHeight = maxHeight
actualWidth = maxWidth
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight))
UIGraphicsBeginImageContext(rect.size)
self.draw(in: rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality)) ?? Data()
UIGraphicsEndImageContext()
return imageData
}