Cotton code
44 lines · 1.8 KB · SwiftRaw
// An album's photos go to a shared album as JPEGs with no metadata (the core refuses EXIF, XMP, IPTC, MPF, comments).import CoreGraphicsimport Foundation@testable import CottonUIimport Testingstruct AlbumsSharedPhotosTests {    /// The markers before the scan, in order.    private func markers(_ data: Data) -> [UInt8] {        let b = [UInt8](data)        var at = 2        var found: [UInt8] = []        while at + 4 <= b.count, b[at] == 0xFF, b[at + 1] != 0xDA {            found.append(b[at + 1])            at += 2 + (Int(b[at + 2]) << 8 | Int(b[at + 3]))        }        return found    }    private func picture(_ w: Int, _ h: Int) -> CGImage {        let c = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!        c.setFillColor(red: 0.2, green: 0.5, blue: 0.3, alpha: 1)        c.fill(CGRect(x: 0, y: 0, width: w, height: h))        return c.makeImage()!    }    @Test func aRenditionIsScaledAndCarriesNoMetadata() throws {        let made = try #require(AlbumsSharedPhotos.jpeg(picture(4000, 3000), longEdge: 2048))        #expect((made.w, made.h) == (2048, 1536))        let seen = markers(made.data)        #expect(!seen.contains(0xE1) && !seen.contains(0xED) && !seen.contains(0xFE))    }    @Test func stripTakesOutExifAndCommentsAndKeepsThePicture() throws {        let made = try #require(AlbumsSharedPhotos.jpeg(picture(64, 48), longEdge: 64))        var bytes = [UInt8](made.data)        let exif: [UInt8] = [0xFF, 0xE1, 0x00, 0x08] + Array("Exif\0\0".utf8)        let comment: [UInt8] = [0xFF, 0xFE, 0x00, 0x05, 0x68, 0x69, 0x21]        bytes.insert(contentsOf: exif + comment, at: 2)        let stripped = AlbumsSharedPhotos.strip(Data(bytes))        #expect(stripped == made.data)    }}