This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/swift sh | |
/* | |
Abstract: | |
Given an image, resize it, creating 1x, 2x and 3x versions for iOS | |
Internally, we use the `sips` tool to perform this resizing, this is just a nice wrapper. | |
*/ | |
import Foundation | |
@discardableResult | |
func shell(_ args: String...) -> Int32 { | |
let task = Process() | |
task.launchPath = "/usr/bin/env" | |
task.arguments = args | |
task.standardOutput = nil // no stdout | |
task.launch() | |
task.waitUntilExit() | |
return task.terminationStatus | |
} | |
guard CommandLine.arguments.count > 2 else { | |
print(""" | |
🔨🌅 iOS/Xcode Image File Resizer | |
To start, provide: | |
-> 🌲 image file path | |
-> 📐 size of the 1x image | |
For example: | |
./resize.swift my_cool_image.png 24 | |
About: | |
-> Images maintain their aspect ratio | |
-> Input image should be at least as large as the @3x output image | |
-> Images are output to the same directory as the parent image | |
-> output images will have '-gen' on the end, and '@2x' or '@3x' designators | |
as needed; 1x images will not have this suffix. | |
""") | |
exit(0) | |
} | |
print("🚴 Running Image Generator...") | |
let filepath = CommandLine.arguments[1] | |
let fileURL = URL(fileURLWithPath: filepath) | |
let filename = fileURL.deletingPathExtension().lastPathComponent | |
let fileExtension = fileURL.pathExtension | |
let parentDirectory = fileURL.deletingLastPathComponent() | |
let desiredSize = CommandLine.arguments[2] | |
guard let sizeLength = Int(desiredSize) else { | |
print("Invalid side length: \(desiredSize), expected an integer") | |
exit(1) | |
} | |
/// the filename that should be output for the original filename and | |
/// the desired output image scale | |
func name(original: String, scale: Int) -> String { | |
var current = original + "-gen" | |
if scale > 1 { | |
current += "@\(scale)x" | |
} | |
current += ".png" | |
return current | |
} | |
for scale in 1...3 { | |
let newFilename = name(original: filename, scale: scale) | |
let newSize = sizeLength * scale | |
let newFilepath = parentDirectory.appendingPathComponent(newFilename) | |
print(" -> Generating \(newFilename)") | |
let result = shell("sips", "-Z", "\(newSize)", filepath, "--out", "\(newFilepath.path)") | |
if result != 0 { | |
print(" ⏎ Error generating \(newFilename)!") | |
} | |
} | |
print("🏆 Completed") | |
exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment