LoginSignup
1

More than 5 years have passed since last update.

Cocoaでswift3.0の画像リサイズ

Posted at

Swift3でCocoaによる画像リサイズのサンプルコード。

以前作成したコードが3になって動かなくなっていたのでリファクタ。

#!/usr/bin/swift


import Cocoa


class fileMG {

    var dir:  String
    var file: String
    var path: String
    var extn: String
    var name: String

    init(p: String) {
        let ns: NSString = p as NSString
        path = p
        file = ns.lastPathComponent
        dir  = ns.deletingLastPathComponent
        extn = ns.pathExtension
        name = (file as NSString).deletingPathExtension
        print("path : \(path)")
        print("file : \(file)")
        print("dir  : \(dir)")
        print("extn : \(extn)")
        print("name : \(name)")
    }
}


class imgMG: fileMG {

    func resizeImg(w: Int, h: Int) -> String {

        if let img: NSImage = NSImage(contentsOfFile: path) {

            let orgBmpRep: NSBitmapImageRep = NSBitmapImageRep(data:img.tiffRepresentation!)!
            let orgRef:    CGImage          = orgBmpRep.cgImage!
            let orgW:      Int              = Int(orgRef.width)
            let orgH:      Int              = Int(orgRef.height)

            var resizeW: Int = 0, resizeH: Int = 0
            if (orgW < orgH) {
                resizeW  = w
                resizeH = orgH * resizeW / orgW
            } else {
                resizeH = h
                resizeW = orgW * resizeH / orgH
            }
            let resizeSize: NSSize = NSMakeSize(CGFloat(resizeW), CGFloat(resizeH))

            let bitsPerComponent: Int          = 8
            let bytesPerRow:      Int          = 4 * resizeW
            let colorSpace:       CGColorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo:       UInt32       = CGImageAlphaInfo.premultipliedLast.rawValue

            let bitmapContext: CGContext = CGContext(data: nil, width: resizeW, height: resizeH, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: UInt32(bitmapInfo))!

            // 元画像 (image) をビットマップに書き出します。
            let bitmapRect: CGRect = NSMakeRect(0.0, 0.0, resizeSize.width, resizeSize.height)
            bitmapContext.draw(orgRef, in: bitmapRect)

            // ビットマップを NSImage に変換します。
            let newImageRef: CGImage = bitmapContext.makeImage()!
            let newImage:    NSImage = NSImage(cgImage: newImageRef, size: resizeSize)

            // 保存
            let newBmpRep:  NSBitmapImageRep    = NSBitmapImageRep(data:newImage.tiffRepresentation!)!
            let imageProps: [String: AnyObject] = [ NSImageCompressionFactor as String: 1.0 as AnyObject ]
            let newData:    NSData              = newBmpRep.representation(using: NSBitmapImageFileType.PNG, properties: imageProps)! as NSData
            let newPath:    String              = "\(dir)/\(name)_\(w).\(extn)"
            newData.write(toFile: newPath, atomically: true)
            return "finish!!\n\(newPath)"
        } else {
            return "not file : " + path

        }
    }
}


///
/// 引数取得
///
if (CommandLine.arguments.count <= 1) {
    print("画像ファイルを指定してください")
    exit(0)
}
var imgResize = imgMG(p: String(CommandLine.arguments[1]))
///
/// 3種類の画像出力
///
print(imgResize.resizeImg(w:  50, h:  50))
print(imgResize.resizeImg(w: 100, h: 100))
print(imgResize.resizeImg(w: 300, h: 300))

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