Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / IdeaArtwork.swift

1import Foundation
2import ImageIO
3import UniformTypeIdentifiers
4
5enum IdeaArtwork {
6 static let platforms = ["x", "linkedin", "reddit", "instagram", "tiktok"]
7
8 static func draftImage(from url: URL, platform: String) throws -> Data {
9 let size: (width: Int, height: Int) = switch platform {
10 case "x": (1600, 900)
11 case "instagram": (1080, 1350)
12 case "tiktok": (1080, 1920)
13 default: (1080, 1080)
14 }
15 guard let image = thumbnail(from: url, maxSize: max(size.width, size.height)),
16 let context = CGContext(data: nil, width: size.width, height: size.height, bitsPerComponent: 8,
17 bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
18 bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {
19 throw WorkspaceError("The idea image couldn’t be opened. Replace it before drafting.")
20 }
21 let width = CGFloat(size.width), height = CGFloat(size.height)
22 let scale = min(width / CGFloat(image.width), height / CGFloat(image.height))
23 let fittedWidth = CGFloat(image.width) * scale, fittedHeight = CGFloat(image.height) * scale
24 context.setFillColor(gray: 1, alpha: 1)
25 context.fill(CGRect(x: 0, y: 0, width: width, height: height))
26 context.interpolationQuality = .high
27 context.draw(image, in: CGRect(x: (width - fittedWidth) / 2, y: (height - fittedHeight) / 2,
28 width: fittedWidth, height: fittedHeight))
29 guard let rendered = context.makeImage(), let jpeg = jpeg(rendered, quality: 0.9) else {
30 throw WorkspaceError("The idea image couldn’t be formatted for this draft.")
31 }
32 return jpeg
33 }
34
35 static func preview(from url: URL) -> Data? {
36 guard let image = thumbnail(from: url, maxSize: 560) else { return nil }
37 for quality in [0.68, 0.5, 0.35] {
38 if let data = jpeg(image, quality: quality), data.count <= 120_000 { return data }
39 }
40 return nil
41 }
42
43 private static func thumbnail(from url: URL, maxSize: Int) -> CGImage? {
44 guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
45 let options = [kCGImageSourceCreateThumbnailFromImageAlways: true,
46 kCGImageSourceCreateThumbnailWithTransform: true,
47 kCGImageSourceThumbnailMaxPixelSize: maxSize] as CFDictionary
48 return CGImageSourceCreateThumbnailAtIndex(source, 0, options)
49 }
50
51 private static func jpeg(_ image: CGImage, quality: Double) -> Data? {
52 let bytes = NSMutableData()
53 guard let destination = CGImageDestinationCreateWithData(bytes, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }
54 CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)
55 return CGImageDestinationFinalize(destination) ? bytes as Data : nil
56 }
57}