From a40bcd96634a621d9dcace2c90814b564a4745e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cihat=20G=C3=BCnd=C3=BCz?= Date: Tue, 13 Oct 2026 13:11:20 +0200 Subject: [PATCH] Encode NSImage.jpegData as JPEG instead of JPEG 2000 The method used the .jpeg2000 file type, so callers expecting a JPEG received a JPEG 2000 file that many consumers (browsers, upload APIs) cannot read. --- .../HandySwiftUI/Extensions/ImageExt.swift | 2 +- Tests/HandySwiftUITests/ImageExtTests.swift | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 Tests/HandySwiftUITests/ImageExtTests.swift diff --git a/Sources/HandySwiftUI/Extensions/ImageExt.swift b/Sources/HandySwiftUI/Extensions/ImageExt.swift index 3d10af4..b6d1058 100644 --- a/Sources/HandySwiftUI/Extensions/ImageExt.swift +++ b/Sources/HandySwiftUI/Extensions/ImageExt.swift @@ -52,7 +52,7 @@ extension Image { else { return nil } return bitmapImage.representation( - using: .jpeg2000, + using: .jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: NSNumber(value: compressionQuality)] ) } diff --git a/Tests/HandySwiftUITests/ImageExtTests.swift b/Tests/HandySwiftUITests/ImageExtTests.swift new file mode 100644 index 0000000..638f2ff --- /dev/null +++ b/Tests/HandySwiftUITests/ImageExtTests.swift @@ -0,0 +1,22 @@ +#if os(macOS) + import AppKit + import Testing + + @testable import HandySwiftUI + + struct ImageExtTests { + @Test + func jpegDataEncodesAsJPEG() throws { + let image = NSImage(size: NSSize(width: 8, height: 8), flipped: false) { rect in + NSColor.systemRed.setFill() + rect.fill() + return true + } + + let data = try #require(image.jpegData(compressionQuality: 0.8)) + + // Every JPEG file starts with the SOI marker followed by the next marker's 0xFF (JPEG 2000 starts with 0x00 0x00 0x00 0x0C) + #expect(Array(data.prefix(3)) == [0xFF, 0xD8, 0xFF]) + } + } +#endif