我对以下脚本中获取输入图像并检查其尺寸的部分遇到问题。如果不是特定尺寸,则会调整图像大小。
我的问题是我应该在 if 块中放入什么来使用 ImageMagick 进行检查?
我当前的代码:
#Change profile picture f(x)
#Ex. changeProfilePicture username /path/to/image.png
function changeProfilePicture() {
userName="$1"
filePath="$(readlink -f "$2")"
fileName="${filePath##*/}" #baseName + fileExtension
baseName="${fileName%.*}"
fileExtension="${filePath##*.}"
echo "Checking if imagemagick is installed..."
if ! command brew ls --versions imagemagick >/dev/null 2>&1; then
echo "Installing imagemagick..."
brew install imagemagick -y
echo "imagemagick has been installed."
else
echo "imagemagick has already been installed."
fi
# check the file extension. If it's not png, convert to png.
echo "Checking file-extension..."
if ! [[ $fileExtension = "png" ]]; then
echo "Converting to ''.png'..."
convert $fileName "${baseName}".png
fileName=$baseName.png
echo "File conversion was successful."
else
echo "File-extension is already '.png'"
fi
# check the dimensions, if its not 96x96, resize it to 96x96.
#I don't know what to put inside the following if-block:
if ! [[ ]]; then
echo "Resizing image to '96x96'..."
convert $fileName -resize 96x96 "${fileName}"
echo "Image resizing was successful."
else
echo "Image already has the dimensions of '96x96'."
fi
echo "changing profile picture to " "$filePath"
sudo cp "$filePath" /var/lib/AccountsService/icons/
cd /var/lib/AccountsService/icons/
sudo mv $fileName "${userName}"
cd ~/Desktop
}
答案1
identify -format '%w %h' your_file
将输出宽度、空格,然后输出高度。
如果你想单独存储每个,你可以这样做:
width =`identify -format '%w' your_file`
height=`identify -format '%h' your_file`
答案2
- 首先,您不太可能拥有 96x96 的现有图片,因此大多数情况下您需要进行转换。您不必识别和比较尺寸。
- 不要信任文件名的扩展名,.png 并不意味着它是 PNG 图像。
- 测试命令然后安装是不必要的检查并且不可移植(apt-get、dnf...等)。事实上,如果发生这种情况,它应该输出“命令未找到”。此外,这种检查可能会减慢您的功能。
那么,为什么不简单地这样做:
#Ex. changeProfilePicture username /path/to/image.png
function changeProfilePicture () {
sudo mkdir -p -- '/var/lib/AccountsService/icons/'"$1"
sudo convert "$2" -set filename:f '/var/lib/AccountsService/icons/'"$1/%t" -resize 96x96 '%[filename:f].png'
}
[笔记]:
警告,请勿在文件名设置中包含文件后缀! IM 将看不到它,并使用原始文件格式保存图像,而不是文件名设置中包含的格式。也就是说文件名将具有您指定的后缀,但图像格式可能不同!