gpt4 book ai didi

ios - 从 UIImageView 获取调整大小的图像

转载 作者:行者123 更新时间:2023-11-28 07:01:12 25 4
gpt4 key购买 nike

我需要将图像数据上传到我的 Parse.com 后端,但我发现我的图片太大了,尺寸不明智。 NSHipster 有一篇关于使用此代码调整图像大小的文章:

import ImageIO

if let imageSource = CGImageSourceCreateWithURL(self.URL, nil) {
let options: CFDictionary = [
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) / 2.0,
kCGImageSourceCreateThumbnailFromImageIfAbsent: true
]

let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options).flatMap { UIImage(CGImage: $0) }
}

不幸的是,这段代码无法在 Swift 1.2 中编译。特别是有2个问题。 CFDictionary 无法初始化,flatMap 方法无法识别。

最佳答案

这里有一些调整图片大小的函数:

import UIKit

func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage {
return RBResizeImage(RBSquareImage(image), size)
}

func RBSquareImage(image: UIImage) -> UIImage {
var originalWidth = image.size.width
var originalHeight = image.size.height

var edge: CGFloat
if originalWidth > originalHeight {
edge = originalHeight
} else {
edge = originalWidth
}

var posX = (originalWidth - edge) / 2.0
var posY = (originalHeight - edge) / 2.0

var cropSquare = CGRectMake(posX, posY, edge, edge)

var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)
}

func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
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
}

来自 HERE .

关于ios - 从 UIImageView 获取调整大小的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32003277/

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