-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.swift
78 lines (63 loc) · 2.07 KB
/
main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// main.swift
// TileCutter
//
// Created by hao on 2017/2/19.
// Copyright © 2017年 Vito. All rights reserved.
//
import Foundation
import AppKit
/*
How to use?
swift (这个main文件所在的目录/main.swift) 需要分割的图片路径
e.g. : swift ~/Project/CoreAnimationDemo/TileCutter/ ~/Pictures/image.jpg
*/
guard CommandLine.argc >= 2 else {
print("TileCutter arguments: inputfile")
exit(1)
}
// input file
let inputFile = CommandLine.arguments[1]
print("inputFile > " + inputFile)
// tile size
let tileSize = 256
// output path
var outputPath = URL(fileURLWithPath: inputFile).deletingPathExtension().absoluteString
print("outputPath > \(outputPath)")
// load image
guard let image = NSImage(contentsOfFile: inputFile) else {
print("load image error")
exit(1)
}
var size = image.size
let representations = image.representations
if let representation = representations.first {
size.width = CGFloat(representation.pixelsWide)
size.height = CGFloat(representation.pixelsHigh)
}
var rect = NSRect(x: 0, y: 0, width: size.width, height: size.height)
guard let imageRef = image.cgImage(forProposedRect: &rect, context: nil, hints: nil) else {
exit(1)
}
// calculate rows and columns
let rows: Int = Int(ceil(Double(size.height) / Double(tileSize)))
let cols: Int = Int(ceil(Double(size.width) / Double(tileSize)))
// generate tiles
for y in 0..<rows {
for x in 0..<cols {
// extract tile image
let tileRect = CGRect(x: x * tileSize, y: y * tileSize, width: tileSize, height: tileSize)
if let tileImage = imageRef.cropping(to: tileRect) {
// convert to jpeg data
let imageRep = NSBitmapImageRep(cgImage: tileImage)
let data = imageRep.representation(using: .JPEG, properties: [:])
// save file
let path = outputPath.appending(String(format: "_%02i_%02i.jpg", x, y))
print(path)
if let url = URL(string: path) {
try? data?.write(to: url, options: Data.WritingOptions.atomic)
}
}
}
}
print("haha")