Skip to content

Instantly share code, notes, and snippets.

@MTattin
Last active August 29, 2015 05:59
Show Gist options
  • Save MTattin/c50dcb4eabd6fcd09905 to your computer and use it in GitHub Desktop.
Save MTattin/c50dcb4eabd6fcd09905 to your computer and use it in GitHub Desktop.
コマンドラインから画像リサイズ(swift1.2) ref: http://qiita.com/MTattin/items/93a8fdf7bb6ad58e8011
#!/usr/bin/swift
import Cocoa
class fileMG {
var dir: String
var file: String
var path: String
var extn: String
init(p: String) {
path = p
file = p.lastPathComponent
dir = p.stringByReplacingOccurrencesOfString(file, withString: "", options: nil, range: nil)
extn = p.pathExtension
}
}
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(CGImageGetWidth(orgRef))
let orgH: Int = Int(CGImageGetHeight(orgRef))
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: CGBitmapInfo = CGBitmapInfo(
CGImageAlphaInfo.PremultipliedLast.rawValue)
let bitmapContext: CGContextRef = CGBitmapContextCreate(
nil,
resizeW,
resizeH,
bitsPerComponent,
bytesPerRow,
colorSpace,
bitmapInfo)
// 元画像 (image) をビットマップに書き出します。
let bitmapRect: CGRect = NSMakeRect(0.0, 0.0, resizeSize.width, resizeSize.height)
CGContextDrawImage(bitmapContext, bitmapRect, orgRef)
// ビットマップを NSImage に変換します。
let newImageRef: CGImageRef = CGBitmapContextCreateImage(bitmapContext)!
let newImage: NSImage = NSImage(CGImage: newImageRef, size: resizeSize)
// p保存
let newBmpRep: NSBitmapImageRep = NSBitmapImageRep(data:newImage.TIFFRepresentation!)!
let imageProps: NSDictionary = NSDictionary(
objects: [1.0] as [AnyObject],
forKeys: [NSImageCompressionFactor] as [AnyObject])
let newData: NSData = newBmpRep.representationUsingType(
NSBitmapImageFileType.NSPNGFileType,
properties: imageProps as [NSObject : AnyObject])!
let wk: [String] = file.componentsSeparatedByString(".")
let newFile: String = wk[0] + "_" + String(w) + "." + extn
let newPath: String = dir.stringByAppendingPathComponent(newFile)
newData.writeToFile(newPath, atomically: true)
return newPath
} else {
return "not file : " + path
}
}
}
if (Process.arguments.count <= 1) {
println("画像ファイルを指定してください")
exit(0)
}
var imgResize = imgMG(p: String(Process.arguments[1]))
println(imgResize.resizeImg(w: 50, h: 50))
println(imgResize.resizeImg(w: 100, h: 100))
println(imgResize.resizeImg(w: 300, h: 300))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment