调整图像大小而不会损失质量
问题描述:
我正在使用以下功能来调整图片的宽度和宽度;高度,但我注意到它会破坏图像质量.
I'm using the functions below to resize my images width & height but I noticed that it ruins the image quality.
class func imageWithSize(image: UIImage,size: CGSize)->UIImage{
if UIScreen.mainScreen().respondsToSelector("scale"){
UIGraphicsBeginImageContextWithOptions(size,false,UIScreen.mainScreen().scale);
}
else
{
UIGraphicsBeginImageContext(size);
}
image.drawInRect(CGRectMake(0, 0, size.width, size.height));
var newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
class func resizeImageWithAspect(image: UIImage,scaledToMaxWidth width:CGFloat,maxHeight height :CGFloat)->UIImage
{
let scaleFactor = width / height;
let newSize = CGSizeMake(width, height);
return imageWithSize(image, size: newSize);
}
还有另一种方法来调整图像大小而又不影响画质吗?或者如何在下面修复我的功能,以免在调整大小后不会破坏图像质量?
Is there another way to resize images without ruining the quality? Or how can I fix my functions below so it doesn't ruin the image quality after resizing?
答
下面是我的代码.对于平方图像,它确实可以很好地工作,并且没有任何质量损失!
Here is my code in swift. For squared images, it works really well and without any loss of quality!
extension UIImage {
func resize(targetSize: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size:targetSize).image { _ in
self.draw(in: CGRect(origin: .zero, size: targetSize))
}
}
}