I have a project I'm working on that requires the original RGB values from an NSImage. When downscaling a completely red image (PNG Image) (RGB: 255,0,0) to a size of 200X200, I get slightly different RGB values (RGB: 251, 0, 7). The resizing code and pixel extraction code are down below. I have two questions. Is this expected behavior when resizing an NSImage using the code below? Is it possible to retain the original RGB values of the image (The RGB values that existed before the downscaling)?
Resizing Code (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
}
The code I used to extract the RGB values from an NSImage is down below:
RGB Extraction Code (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)
}
}