// // Image.swift // PrySDR // // Created by Jacky Jack on 27/12/2024. // import Foundation import AppKit // https://stackoverflow.com/questions/30958427/pixel-array-to-uiimage-in-swift public struct PixelData { var a: UInt8 var r: UInt8 var g: UInt8 var b: UInt8 } public class SimpleImage { private var pixels: [PixelData] = [] private var width:Int = 0 private var height:Int = 0 init(width: Int, height: Int) { self.width = width self.height = height pixels = .init(repeating: .init(a: 255, r: 0, g: 0, b: 0), count: width*height) } func drawPalletLine(line: Int, pixelLine:[Float]) { for i in 0..255.0 { //print("values to high") pixel = 255.0 } if pixel < 0.0 { pixel = 0.0 } self.pixels[line*self.width + i].a = 255 self.pixels[line*self.width + i].r = UInt8(pixel) self.pixels[line*self.width + i].g = UInt8(pixel) self.pixels[line*self.width + i].b = UInt8(pixel) } } func drawPixel(_ w: Int, _ h: Int, _ pixel: PixelData) { self.pixels[h*self.height+w] = pixel } func toCGImage() -> CGImage? { guard self.width > 0 && self.height > 0 else { return nil } guard self.pixels.count == self.width * self.height else { return nil } let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) let bitsPerComponent = 8 let bitsPerPixel = 32 var data = self.pixels // Copy to mutable [] guard let providerRef = CGDataProvider(data: NSData(bytes: &data, length: data.count * MemoryLayout.size) ) else { return nil } guard let cgim = CGImage( width: self.width, height: self.height, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: self.width * MemoryLayout.size, space: rgbColorSpace, bitmapInfo: bitmapInfo, provider: providerRef, decode: nil, shouldInterpolate: true, intent: .defaultIntent ) else { return nil } return cgim } func toNSImage() -> NSImage? { guard let cgim = toCGImage() else { return nil } return NSImage(cgImage: cgim, size:.zero) } func saveAsJPEG(_ image: NSImage, _ name: String) { if let imageData = image.tiffRepresentation { do { let bundlePath = Bundle.main.resourcePath! let imageUrl = URL(fileURLWithPath:bundlePath+"/"+name) try imageData.write(to: imageUrl) } catch { print("Cant save image to disk") } } else { print("cant get tiff representation") } } func saveAsJPEG(_ name: String) { if let img = self.toNSImage() { saveAsJPEG(img, name) } } }