I thought I’d share with you my img2base64 bash script. It uses common Linux tools to convert any image to a base64 representation and then encode the data within tags which can be immediately pasted into Obsidian. The script outputs to the clipboard for convenience.
Install by copying contents to a file and then run chmod +x <file>
to make it executable. Optionally move the file to /usr/bin to make it accessible to everybody. Or run as ./<file>
from the current directory.
#!/bin/bash
# Convert an image file into MarkDown base64.
# The converted image is copied to clipboard,
# original image is unchanged.
# Check if xclip is installed
if ! command -v xclip &>/dev/null; then
echo "Error: xclip is not installed. Please install it before running this program."
exit 1
fi
# Check if base64 is installed
if ! command -v base64 &>/dev/null; then
echo "Error: base64 is not installed. Please install it before running this program."
exit 1
fi
# Check if at least one argument is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <image-file>"
exit 1
fi
# Get the first argument
image_file="$1"
# Check if the image file exists
if [ ! -e "$image_file" ]; then
echo "Error: The file $image_file does not exist."
exit 1
fi
# Get the file extension
file_extension="${image_file##*.}"
# List of known image file extensions (you can extend this list)
image_extensions=("jpg" "jpeg" "png" "gif" "bmp")
# Check if the file extension is in the list of known image file extensions
if [[ " ${image_extensions[@]} " =~ " ${file_extension,,} " ]]; then
base64=$(base64 -w 0 $image_file)
if [ $? -eq 0 ]; then
output=""
# Copy the variable to the clipboard
echo -n "$output" | xclip -selection clipboard
echo "Variable copied to clipboard: $my_variable"
exit 0
else
echo "Error: Unable to convert to base64."
exit 1
fi
else
echo "Error: The provided file '$image_file' is not an image file."
exit 1
fi