Bash脚本创建自定义缩略图

Raj*_*mar 5 linux shell imagemagick thumbnails

我需要一个bash脚本来将所有图像保存在指定的文件夹中;采取分辨率,如果分辨率低于最小值,则不执行任何操作,否则请创建中等拇指图像(200x150像素)。

我在Windows中使用Imagemagick。但是在Linux上,我不能使用相同的脚本,因此需要编写一个新脚本。

到目前为止,这就是我提出的。

#!/bin/bash
for files in /path/to/image/*
  do
       TESTFILE=`echo "$files" | sed 's/|/ /g' | xargs file -b | awk '{print $1}'`
       while read F
       CHECKSIZE=`file "$TESTFILE" -b | sed 's/ //g' | sed 's/,/ /g' | awk  '{print $2}' | sed 's/x/ /g' | awk '{print $1}'`
     if [ $CHECKSIZE -ge  200  ]; then
        convert -sample 200x150 "$F" "$F{_thumb}"
     fi
    done
  done
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此脚本时,它没有给我缩略图也没有给我任何错误。我对这些脚本非常陌生。

更新:

我想出了这个脚本,谢谢大家。但是现在我需要一个帮助。现在我想将新图像存储在图像文件夹内的文件夹中。例如,/ home / image是所有文件所在的位置。我希望将拇指图像存储在/ home / image / thumbs中。我也想将文件重命名为filename_thumb.jpg,但是以下脚本的问题是它存储为filename.jpg_thumb

#!/bin/bash
THUMBS_FOLDER=/home/temp/thumbs
for file in /home/temp/*
do
  # next line checks the mime-type of the file
  IMAGE_TYPE=`file --mime-type -b "$file" | awk -F'/' '{print $1}'`
  if [ x$IMAGE_TYPE = "ximage" ]; then
      IMAGE_SIZE=`file -b $file | sed 's/ //g' | sed 's/,/ /g' | awk  '{print $2}'`
      WIDTH=`identify -format "%w" "$file"`
      HEIGHT=`identify -format "%h" "$file"`           
      # If the image width is greater that 200 or the height is greater that 150 a thumb is created
     if [ $WIDTH -ge  201 ] || [ $HEIGHT -ge 151 ]; then
        #This line convert the image in a 200 x 150 thumb 
        filename=$(basename "$file")
        extension="${filename##*.}"
        filename="${filename%.*}"
        convert -sample 200x150 "$file" "${THUMBS_FOLDER}/${filename}_thumb.${extension}"   
     fi
  fi     
done
Run Code Online (Sandbox Code Playgroud)

sgr*_*roh 4

另一种不使用 imageinfo 的方法:

请记住更改图像路径,在我的例子中,我在同一文件夹级别使用名为 imgs 的文件夹。

将内容复制到名为 create_thumbs.sh 的文件中,然后粘贴以下代码:

#!/bin/bash
THUMBS_FOLDER=/home/image/thumb
for file in /home/image/*
do
  # next line checks the mime-type of the file
  IMAGE_TYPE=`file --mime-type -b "$file" | awk -F'/' '{print $1}'`
  if [ x$IMAGE_TYPE = "ximage" ]; then
      IMAGE_SIZE=`file -b $file | sed 's/ //g' | sed 's/,/ /g' | awk  '{print $2}'`
      WIDTH=`echo $IMAGE_SIZE | sed 's/x/ /g' | awk '{print $1}'`
      HEIGHT=`echo $IMAGE_SIZE | sed 's/x/ /g' | awk '{print $2}'`           
      # If the image width is greater that 200 or the height is greater that 150 a thumb is created
     if [ $WIDTH -ge  201 ] || [ $HEIGHT -ge 151 ]; then
        #This line convert the image in a 200 x 150 thumb 
        filename=$(basename "$file")
        extension="${filename##*.}"
        filename="${filename%.*}"
        convert -sample 200x150 "$file" "${THUMBS_FOLDER}/${filename}_thumb.${extension}"   
     fi
  fi     
done
Run Code Online (Sandbox Code Playgroud)

调用它:

bash create_thumbs.sh
Run Code Online (Sandbox Code Playgroud)