1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
//
// 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..<self.width {
var pixel = pixelLine[i]
if pixel>256.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<PixelData>.size)
)
else { return nil }
guard let cgim = CGImage(
width: self.width,
height: self.height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: self.width * MemoryLayout<PixelData>.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)
}
}
}
|