Skip to content

Instantly share code, notes, and snippets.

@callmetwan
Last active November 12, 2020 21:57
Show Gist options
  • Save callmetwan/9ef5f348afe3070dc7cbd603ccc048a8 to your computer and use it in GitHub Desktop.
Save callmetwan/9ef5f348afe3070dc7cbd603ccc048a8 to your computer and use it in GitHub Desktop.
Generate JS object of images' filename, width, and height
#!/bin/bash
resultsFile=$PWD/results.txt
echo "" > $resultsFile
recursiveImageGen() {
for arg in *; do
if [ -d "$arg" ]; then
(cd -- "$arg" && recursiveImageGen)
fi
results=$(sips -g pixelHeight -g pixelWidth $arg)
filenameRegex="[ \w-]+?(?=\.)"
filename=$(echo "$results" | ggrep -oP "$filenameRegex")
if [[ -n $filename ]]; then
pixelHeightRegex='pixelHeight: \K([0-9]*)'
pixelHeight=$(echo "$results" | ggrep -oP "$pixelHeightRegex")
pixelWidthRegex="pixelWidth: \K([0-9]*)"
pixelWidth=$(echo "$results" | ggrep -oP "$pixelWidthRegex")
echo "$filename: {uri: '$filename', width: $pixelWidth, height: $pixelHeight}," >> $resultsFile
fi
done
}
recursiveImageGen
sort -o $resultsFile $resultsFile
echo '{' | cat - $resultsFile > temp && mv temp $resultsFile
echo '}' >> $resultsFile
# replace open with your specific editor if not system default
open $resultsFile
@callmetwan
Copy link
Author

I had a number of images that I would be referencing from a JS app. I needed their filename, width, and height formatted into an object, with the filename as the key.

This will walk through the current directory recursively.

sips is used to get the image information. It spit out complaints about any files it cannot understand.

If you're on a Mac, the version of grep that ships doesn't have the ability to run regex in Perl mode (-P flag on line 13), you'll need to install it (homebrew is easiest: brew install grep). It aliases to ggrep, initialized from GNU Grep.

Finally, I'm not a bash maven, there is certainly a more performant way to do this. More than happy to update this with suggestions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment