调整大小(缩小尺寸)NSImage稍微改变RGB值。如何保留原始RGB值?

时间:2016-12-27 20:50:34

标签: ios swift cocoa image-processing

我有一个项目,我需要NSImage的原始RGB值。当将完全红色的图像(PNG图像)(RGB:255,0,0)缩小到200X200的大小时,我会得到略微不同的RGB值(RGB:251,0,7)。调整大小代码和像素提取代码在下面。我有两个问题。使用下面的代码调整NSImage大小时,这是预期的行为吗?是否可以保留图像的原始RGB值(降尺度之前存在的RGB值)?

调整代码(credit)

open func resizeImage(image:NSImage, newSize:NSSize) -> NSImage{

    let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(newSize.width), pixelsHigh: Int(newSize.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)

    rep?.size = newSize

    NSGraphicsContext.saveGraphicsState()
    let bitmap = NSGraphicsContext.init(bitmapImageRep: rep!)
    NSGraphicsContext.setCurrent(bitmap)
    image.draw(in: NSMakeRect(0, 0, newSize.width, newSize.height), from: NSMakeRect(0, 0, image.size.width, image.size.height), operation: .sourceOver, fraction: CGFloat(1))

    let newImage = NSImage(size: newSize)
    newImage.addRepresentation(rep!)
    return newImage

}

我用来从NSImage中提取RGB值的代码如下:

RGB提取代码(credit)

extension NSImage {

    func pixelData() -> [Pixel] {
        var bmp = self.representations[0] as! NSBitmapImageRep
        var data: UnsafeMutablePointer<UInt8> = bmp.bitmapData!
        var r, g, b, a: UInt8
        var pixels: [Pixel] = []

        NSLog("%d", bmp.pixelsHigh)
        NSLog("%d", bmp.pixelsWide)
        for var row in 0..<bmp.pixelsHigh {
            for var col in 0..<bmp.pixelsWide {
                r = data.pointee
                data = data.advanced(by: 1)
                g = data.pointee
                data =  data.advanced(by: 1)
                b = data.pointee
                data =  data.advanced(by: 1)
                a = data.pointee
                data =  data.advanced(by: 1)
                pixels.append(Pixel(r: r, g: g, b: b, a: a))
            }
        }

        return pixels
    }
}

class Pixel {

    var r: Float!
    var g: Float!
    var b: Float!

    init(r: UInt8, g: UInt8, b: UInt8, a: UInt8) {
        self.r = Float(r)
        self.g = Float(g)
        self.b = Float(b)
    }

}

1 个答案:

答案 0 :(得分:0)

由于@KenThomases,问题已得到解决。调整NSImage的大小时,我将NSBitmapImageRep对象的颜色空间设置为NSCalibratedRGBColorSpace。缩小之前的原始NSImage具有与缩小的图像不同的颜色空间名称。颜色空间的简单变化产生了正确的结果。 NSCalibratedRGBColorSpace已更改为NSDeviceRGBColorSpace