从 Linux 命令行向图像添加时间戳

And*_*rew 10 linux timestamp images

我有一个装满图像的文件夹。我正在尝试根据创建文件的日期为每个图像添加一个时间戳到图像本身。这可能吗?我在这里读过这篇文章,但它使用了 exif 数据。我的图片没有 exif 数据。

我可以使用创建的日期直接添加时间戳吗?还是我必须使用exif数据?如果我必须使用 exif 数据,我将如何使用创建日期来编写它?

我使用的是没有 GUI 的 Ubuntu Server,所以我需要一个命令行解决方案。任何人都可以帮忙吗?谢谢!

ter*_*don 19

如果您想将图像文件的创建日期写入图像本身(如果这不是您想要的,请编辑您的问题),您可以使用imagemagick.

  1. 如果尚未安装 ImageMagick,请安装:

    sudo apt-get install imagemagick
    
    Run Code Online (Sandbox Code Playgroud)
  2. 运行一个 bash 循环,它将获取每张照片的创建日期,并convertimagemagick套件中使用来编辑图像:

    for img in *jpg; do convert "$img" -gravity SouthEast -pointsize 22 \
       -fill white -annotate +30+30  %[exif:DateTimeOriginal] "time_""$img"; 
    done
    
    Run Code Online (Sandbox Code Playgroud)

    对于每个名为 的图像foo.jpg,这将创建一个副本time_foo.jpg,其名称为右下角的时间戳。对于多种文件类型和漂亮的输出名称,您可以更优雅地执行此操作,但语法稍微复杂一些:

好的,那是简单的版本。我写了一个脚本,可以处理更复杂的情况,子目录中的文件,奇怪的文件名等。据我所知,只有 .png 和 .tif 图像可以包含 EXIF 数据,所以没有必要在其他格式上运行它. 但是,作为一种可能的解决方法,您可以使用文件的创建日期而不是 EIF 数据。这很可能与拍摄图像的日期不同,因此下面的脚本已注释掉相关部分。如果您希望它以这种方式处理,请删除注释。

将此脚本另存为add_watermark.sh并在包含文件的目录中运行它:

bash /path/to/add_watermark.sh
Run Code Online (Sandbox Code Playgroud)

它使用exiv2您可能需要安装的 ( sudo apt-get install exiv2)。剧本:

#!/usr/bin/env bash

## This command will find all image files, if you are using other
## extensions, you can add them: -o "*.foo"
find . -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.tif" -o \
 -iname "*.tiff" -o -iname "*.png" | 

## Go through the results, saving each as $img
while IFS= read -r img; do
    ## Find will return full paths, so an image in the current
    ## directory will be ./foo.jpg and the first dot screws up 
    ## bash's pattern matching. Use basename and dirname to extract
    ## the needed information.
    name=$(basename "$img")
    path=$(dirname "$img")
    ext="${name/#*./}"; 

    ## Check whether this file has exif data
    if exiv2 "$img" 2>&1 | grep timestamp >/dev/null 
    ## If it does, read it and add the water mark   
    then
    echo "Processing $img...";
    convert "$img" -gravity SouthEast  -pointsize 22 -fill white \
             -annotate +30+30  %[exif:DateTimeOriginal] \
             "$path"/"${name/%.*/.time.$ext}";
    ## If the image has no exif data, use the creation date of the
    ## file. CAREFUL: this is the date on which this particular file
    ## was created and it will often not be the same as the date the 
    ## photo was taken. This is probably not the desired behaviour so
    ## I have commented it out. To activate, just remove the # from
    ## the beginning of each line.

    # else
    #   date=$(stat "$img" | grep Modify | cut -d ' ' -f 2,3 | cut -d ':' -f1,2)
    #   convert "$img" -gravity SouthEast  -pointsize 22 -fill white \
    #          -annotate +30+30  "$date" \
    #          "$path"/"${name/%.*/.time.$ext}";
    fi 
done
Run Code Online (Sandbox Code Playgroud)