Skip to content

Instantly share code, notes, and snippets.

Last active June 19, 2020 17:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
#!/usr/bin/swift sh
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
func shell(_ args: String...) -> Int32 {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.standardOutput = nil // no stdout
return task.terminationStatus
guard CommandLine.arguments.count > 2 else {
🔨🌅 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
-> 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.
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")
/// 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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment