在我的應用程序中,我需要在服務器上上傳照片,所以在此之前,我想調整大小並將它們壓縮到可接受的大小。我試圖調整它們的大小有兩種方式,而第一種方式是:如何在UIImage調整大小時提高清晰度?
// image is an instance of original UIImage that I want to resize
let width : Int = 640
let height : Int = 640
let bitsPerComponent = CGImageGetBitsPerComponent(image.CGImage)
let bytesPerRow = CGImageGetBytesPerRow(image.CGImage)
let colorSpace = CGImageGetColorSpace(image.CGImage)
let bitmapInfo = CGImageGetBitmapInfo(image.CGImage)
let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: CGFloat(width), height: CGFloat(height))), image.CGImage)
image = UIImage(CGImage: CGBitmapContextCreateImage(context))
另一種方式:
image = RBResizeImage(image, targetSize: CGSizeMake(640, 640))
func RBResizeImage(image: UIImage?, targetSize: CGSize) -> UIImage? {
if let image = image {
let size = image.size
let widthRatio = targetSize.width/image.size.width
let heightRatio = targetSize.height/image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width heightRatio, size.height heightRatio)
} else {
newSize = CGSizeMake(size.width widthRatio, size.height widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
} else {
return nil
}
}
在那之後,我用UIImageJPEGRepresentation
壓縮UIImage的,但即使compressionQuality
是1,照片仍然模糊不清(這在物體邊緣大多可見,也許這不是什麼大問題,但照片比Instagram上的同一張照片大三至五倍,例如但不具有相同的清晰度)。當然,對於0.5而言,情況更糟,照片的尺寸仍然大於Instagram的相同照片。
照片來自我的應用程序,compressionQuality設置爲1時,邊緣模糊,大小爲341 KB
照片來自Instagram的,邊緣是鋒利的,並且尺寸是136 KB
編輯:
好的,但我現在有點困惑,我不知道該怎麼做,以 保持縱橫比?這是我如何裁剪圖像(scrollView具有UIImageView,所以我可以移動和縮放圖像,並在最後,我能夠裁剪scrollView的可見部分是sqare)。無論如何,從上面的圖像最初是2048x2048,但它仍然模糊。
var scale = 1/scrollView.zoomScale
var visibleRect : CGRect = CGRect()
visibleRect.origin.x = scrollView.contentOffset.x * scale
visibleRect.origin.y = scrollView.contentOffset.y * scale
visibleRect.size.width = scrollView.bounds.size.width * scale
visibleRect.size.height = scrollView.bounds.size.height * scale
image = crop(image!, rect: visibleRect)
func crop(srcImage : UIImage, rect : CGRect) -> UIImage? {
var imageRef = CGImageCreateWithImageInRect(srcImage.CGImage, rect)
var cropped = UIImage(CGImage: imageRef)
return cropped
}
HTTP:/ /stackoverflow.com/questions/28809355/resize-uiimage-not-give-me-exact-new-size-after-resize-it/28809573#28809573 – user4261201
我也試過,但我得到了相同的結果。上面的照片再次是341 KB,並且每個像素都保持不變。 – Marko