我正在尝试调整 NSImage 的大小以将其与 parse 作为 PFFile 一起使用,并且我需要更改其尺寸以减小其数据大小,但它不起作用。调整大小的图像在 Swift 中调整了宽度和高度,但它与原始图像保持相同的尺寸。
该图像是 2560 x 1706 和 721 KB 的 JPG。
当我将它传递给数据时,它保持相同的尺寸并达到 5.7 MB
这是我的代码:
let fotoNSImage = NSImage(byReferencing: url)
let fotoNSImageRedim = redimensionaNSImage(imagem: fotoNSImage, tamanho: NSSize(width: 200, height: 200))
let fotoNSImageRep = NSBitmapImageRep(data: (fotoNSImageRedim.tiffRepresentation)!)
let fotoNSImagePng = fotoNSImageRep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])
let fotoProduto = FotoProduto(foto: PFFile(data: fotoNSImagePng!)!, categorias: [])
调整图像大小的方法:
static func redimensionaNSImage(imagem: NSImage, tamanho: NSSize) -> NSImage {
var ratio: Float = 0.0
let imageWidth = Float(imagem.size.width)
let imageHeight = Float(imagem.size.height)
let maxWidth = Float(tamanho.width)
let maxHeight = Float(tamanho.height)
if (imageWidth > imageHeight) {
// Landscape
ratio = maxWidth / imageWidth;
}
else {
// Portrait
ratio = maxHeight / imageHeight;
}
// Calculate new size based on the ratio
let newWidth = imageWidth * ratio
let newHeight = imageHeight * ratio
// Create a new NSSize object with the newly calculated size
let newSize: NSSize = NSSize(width: Int(newWidth), height: Int(newHeight))
// Cast the NSImage to a CGImage
var imageRect: CGRect = CGRect(x: 0, y: 0, width: Int(newWidth), height: Int(newHeight))
let imageRef = imagem.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
// Create NSImage from the CGImage using the new size
let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize)
// Return the new image
return imageWithNewSize
}
我已经尝试了以下方法但没有成功。
1 - 直接在 fotoNSImagePng 上更改 pixelWide 和 pixelHigh:
fotoNSImageRep?.pixelsWide = 200
fotoNSImageRep?.pixelsHigh = 133
2 - 创建一个新的 NSBitmapImageRep 并用它替换图像表示:
let rep = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: 200,
pixelsHigh: 133,
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSDeviceRGBColorSpace,
bytesPerRow: Int(newSize.width * 4),
bitsPerPixel: 32)
3 - 遵循这种方法: 如何调整大小 - 重新采样 - 更改文件大小 - NSImage
4 - 更改 NSBitmapImageRep 大小值:
fotoNSImageRep?.size.width = 200
fotoNSImageRep?.size.height = 133
到目前为止没有任何效果。