如何调整大小 - 重新采样 - 更改文件大小 - NSImage

问题描述 投票:0回答:1

我在google上搜索了很多,跟踪了很多GitHub代码,但没有成功。

我需要读取一个 jpeg 文件,例如 DPI = 72,大小 = 16000x1096 然后,我需要调整它的大小,以便保存 72 DPI、800x548 像素的 jpeg 文件 这个,在 OSX 下,所以我可以使用 NSIMAGE,而不是 UIImage!

我不在乎是否失去一些品质!

最后,经过多次尝试,我把最新的代码放在这里,并需要一些帮助:

    // get source image, jpeg, 1600x1196, 72 dpi
    let sourceImage = NSImage(contentsOfFile: source)

    // compute the scale, to have the longest size = 800 pixels. 72 DPI
    let width = CGFloat(sourceImage!.size.width)
    let height = CGFloat(sourceImage!.size.height)
    var scale = CGFloat( 800.0 / width)
    if width < height {
        scale = 800.0 / height
    }
    let newSize:NSSize = NSSize(width: Int(width * scale), height: Int(height * scale))
    print ("new size : " + String(describing: newSize) )

    // create a new image, with the "small" size
    let newImage = NSImage(size: NSSize(width: newSize.width, height: newSize.height))
    // lockfocus : draw will be done in this image
    newImage.lockFocus()
    // interpolation = low, because I don't care of quality
    NSGraphicsContext.current()?.imageInterpolation = NSImageInterpolation.low
    // draw the big image, into the small one
    sourceImage!.draw(in: NSMakeRect(0, 0, newSize.width, newSize.height), from: NSMakeRect(0, 0, width, height), operation: NSCompositingOperation.copy, fraction: CGFloat(1.0))
    newImage.unlockFocus()

    print("newImage size: " + String(describing: newImage.size))
    // display : newImage size: 800 x 598

    let cgRef = newImage.cgImage(forProposedRect: nil, context: nil, hints: nil)
    let newRep = NSBitmapImageRep(cgImage: cgRef!)
    newRep.size = newSize

    let jfifProperties = NSDictionary(dictionary: [kCGImagePropertyJFIFIsProgressive:kCFBooleanTrue])
    let properties = NSDictionary(dictionary: [kCGImageDestinationLossyCompressionQuality:1.0,
                                               kCGImagePropertyJFIFDictionary:jfifProperties,
                                               kCGImagePropertyDPIHeight: 72.0,
                                               kCGImagePropertyDPIWidth:72.0,
                                               kCGImagePropertyPixelHeight: 1.0,
                                               kCGImagePropertyPixelWidth: 1.0
                                               ])

    let data = newRep.representation(using: .JPEG, properties: properties as! [String : Any]) //[:])
    do {
        let url = URL(string: "file://" + destination)
        try data?.write(to: url!) //, options: false)
    }
    catch let error as NSError {
        resizeError = error.localizedDescription
        return false
    }

此代码无法正常工作。我获得一个文件,其分辨率为 144 DPI,分辨率为 1600 x 1096!

如果我在调试器下打印变量 newImage,它会显示以下内容:

newImage的打印说明: < (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; Color LCD)> 宽度 = 1600,高度 = 1196,bpc = 8,bpp = 32,行字节 = 6400 kCGImageAlphaPremultipliedFirst | kCGImageAlphaPremultipliedFirst | kCGImageByteOrder32Little 是面具?没有,有口罩吗?不是,有哑光吗?不,应该插值吗?是>”

正如我们所看到的,内容似乎与原始内容具有相同的大小,不是吗?

我真的需要一些帮助,拜托,我被屏蔽了,找不到任何解决方案。

感谢您的回答,谁能帮助我。

致以诚挚的问候 奥利维尔

swift macos swift3 jpeg nsimage
1个回答
2
投票

我自己找到了解决方案,但我很感激人们试图帮助我。谢谢你。

这是我修复它的方法:

    // get source image, jpeg, 1600x1196, 72 dpi
    let sourceImage = NSImage(contentsOfFile: source)

    // compute the scale, to have the longest size = 800 pixels. 72 DPI
    let width = CGFloat(sourceImage!.size.width)
    let height = CGFloat(sourceImage!.size.height)
    var scale = CGFloat( resizedLongestSize / width)
    if width < height {
        scale = resizedLongestSize / height
    }
    let newSize:NSSize = NSSize(width: Int(width * scale), height: Int(height * scale))

    // create NSBitmapRep manually, if using cgImage, the resulting size is wrong
    let rep = NSBitmapImageRep(bitmapDataPlanes: nil,
                               pixelsWide: Int(newSize.width),
                               pixelsHigh: Int(newSize.height),
                               bitsPerSample: 8,
                               samplesPerPixel: 4,
                               hasAlpha: true,
                               isPlanar: false,
                               colorSpaceName: NSDeviceRGBColorSpace,
                               bytesPerRow: Int(newSize.width * 4),
                               bitsPerPixel: 32)
    
    let ctx = NSGraphicsContext(bitmapImageRep: rep!)
    NSGraphicsContext.saveGraphicsState()
    NSGraphicsContext.setCurrent( ctx )
    sourceImage!.draw(in: NSMakeRect(0, 0, newSize.width, newSize.height))
    ctx?.flushGraphics()
    NSGraphicsContext.restoreGraphicsState()
    
    // Get NSData, and save it
    let data = rep?.representation(using: .JPEG, properties: [:]) // properties as! [String : Any]) //
    do {
        let url = URL(string: "file://" + destination)
        try data?.write(to: url!) //, options: false)
    }
    catch let error as NSError {
        resizeError = error.localizedDescription
        return false
    }

此代码生成一个调整大小的图像文件,其中包含一组有限的 EXIF 数据,如果需要,可以很容易填充。

© www.soinside.com 2019 - 2024. All rights reserved.