我想调整UIImage的大小,以便能够将其上传到parse.com。我想在不挤压的情况下调整大小。我怎样才能确保它足够小,可以上传到parse.com(10485760字节),但不能将其压缩到设定的大小。 这是我在下面尝试的代码,但显然确切地设置了图像大小。 有什么想法吗?
var newSize:CGSize = CGSize(width: 600,height: 600)
let rect = CGRectMake(0,0, newSize.width, newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
// image is a variable of type UIImage
profileImage?.drawInRect(rect)
profileImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
答案 0 :(得分:3)
尝试使用此方法缩放图像,同时保持纵横比:
func scaleImage(image: UIImage, maxDimension: CGFloat) -> UIImage {
var scaledSize = CGSize(width: maxDimension, height: maxDimension)
var scaleFactor: CGFloat
if image.size.width > image.size.height {
scaleFactor = image.size.height / image.size.width
scaledSize.width = maxDimension
scaledSize.height = scaledSize.width * scaleFactor
} else {
scaleFactor = image.size.width / image.size.height
scaledSize.height = maxDimension
scaledSize.width = scaledSize.height * scaleFactor
}
UIGraphicsBeginImageContext(scaledSize)
image.drawInRect(CGRectMake(0, 0, scaledSize.width, scaledSize.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
在这种情况下,您可以这样称呼它:
profileImage = scaleImage(profileImage, newSize: CGSizeMake(600, 600))