Skip to content

Instantly share code, notes, and snippets.

@bradleymackey
Last active June 19, 2020 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradleymackey/66eebe7ed323830ff6dc5d3ca249482a to your computer and use it in GitHub Desktop.
Save bradleymackey/66eebe7ed323830ff6dc5d3ca249482a to your computer and use it in GitHub Desktop.
#!/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