1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:左右反転した画像,白黒画像,ネガポジ反転画像を生成する

Last updated at Posted at 2019-07-02

NSImageにはサイズとピクセルサイズの概念がある(これはRetinaディスプレイ5Kディスプレイへの対応のため)が,NSImageに対してそのままアフィン変換を適用したら,画像のピクセルサイズがおかしくなってしまった.これを避ける方法を色々試した結果,一旦CIFilterを咬ませる方法が良さそうだとわかった.

フィルタのソース
extension NSImage {
    public var ciImage: CIImage? {
        guard let imageData = self.tiffRepresentation else { return nil }
        return CIImage(data: imageData)
    }

    public var flipped: NSImage {
        guard let flipFilter = CIFilter(name: "CIAffineTransform") else { return self }
        flipFilter.setValue(self.ciImage, forKey: kCIInputImageKey)
        flipFilter.setValue(CGAffineTransform(a: -1, b: 0, c: 0, d: 1, tx: self.size.width, ty: 0), forKey: kCIInputTransformKey)
        guard let output = flipFilter.outputImage else { return self }
        let rep = NSCIImageRep(ciImage: output)
        let nsImage = NSImage(size: rep.size)
        nsImage.addRepresentation(rep)
        return nsImage
    }

    public var mono: NSImage {
        guard let monoFilter = CIFilter(name: "CIPhotoEffectMono") else { return self }
        monoFilter.setValue(self.ciImage, forKey: kCIInputImageKey)
        guard let output = monoFilter.outputImage else { return self }
        let rep = NSCIImageRep(ciImage: output)
        let nsImage = NSImage(size: rep.size)
        nsImage.addRepresentation(rep)
        return nsImage
    }
    
    public var inverted: NSImage {
        guard let invertFilter = CIFilter(name: "CIColorInvert") else { return self }
        invertFilter.setValue(self.ciImage, forKey: kCIInputImageKey)
        guard let output = invertFilter.outputImage else { return self }
        let rep = NSCIImageRep(ciImage: output)
        let nsImage = NSImage(size: rep.size)
        nsImage.addRepresentation(rep)
        return nsImage
    }
}
使用例
let original = NSImage(imageLiteralResourceName: "Sample")

let flippedImage = original.flipped
let monoImage = original.mono
let invertedImage = original.inverted
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?