0
從具有透明背景的NSImage提取RGB值時,我獲得了特定圖像內實際顏色對象的正確RGB值,但我也獲得了(0,0,0)的RGB值,即使沒有在我測試的特定圖像內看到黑色像素。我的猜測是我從透明圖像的部分獲得(0,0,0)。我如何只有獲得圖像的RGB值減去透明背景。這種行爲發生在我調整圖像大小並用下面的代碼提取像素值時。爲什麼我爲具有透明背景的NSImage獲取(0,0,0)的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: NSDeviceRGBColorSpace, 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)
}
}
我還嘗試將調整大小代碼的繪製方法中的操作參數更改爲.copy,但沒有運氣。
非常感謝! (我接受答案,但我得等7分鐘點擊檢查按鈕哈哈) – Guled