〔Java〕简单的根据拍照时间重命名图片

java处理EXIF信息方法 资料处理了关于照片exif的信息,着重处理了照片中的gps信息, 立即下载

 

一直使用ACDsee8的根据图片拍照时间来批量重命名图片,但是让人讨厌的是:

1.ACDsee8经常把前面的零省略,造成名称不能对齐,如2007-08-08 08-08-08它改成2007-08-08 8-8-8;

2.另外,ACDsee8使用了本地计算机的时间设置,如果你变动了时间设置,那么以后修改的样式也会跟着变动。

Bug:

1.由于一些图片的Exif信息过于靠后,在10KB后面,而我为了速度,只读取前面的10KB,所以一些图片可能不能改名。我现在准备分批读取前20480个字节(经过统计,已知最远的在16000字节左右),但要考虑隔断区的连接问题,有空再写了。

2.如果图片有重复,那么会在后面增加数字序列(从001到999999),然而第一个重复的,已经改好名的,没有数字序列的图片怎么办?添加序列号为000?添加完以后,第三个又会改成没有序列号的,莫非真要作二次循环?以后再写。

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;


/*******************************************************************************
 *
 * 读出数码图片中的拍照时间
 *
 *
 * 原理:
 *
 * 1、由于数码图片的拍照时间可以直接从图片中搜索到,所以本例不需要分析EXIF的格式。
 *
 * 2、正常的(Normal)数码图片,会有三处到四处的时间,其中第二、第三处固定在一起,
 *
 *    第二处是图片拍摄时间,第三处是图片存储时间,一般两者相同,他们之间用NULL值
 *
 *    分隔(ASCII值为0),如下:
 *
 *    2001:01:02 12:23:56[NULL]2001:01:02 12:23:56[NULL]
 *
 *    两者位置不定,但格式好查找,八个冒号,两个空格,两个NULL值,其余为数字。
 *
 *    不用考虑01:09:34被压缩为1:9:34这样的特例,见EXIF2.1规范关于时间的三段:
 *
 *    1. DateTime(第一处,修改时间)
 *
 *    The date and time of image creation. In this standard it is the date and time
 *
 *    the file was changed.
 *
 *    The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
 *
 *    the date and time separated by one blank character [20.H].
 *
 *    When the date and time are unknown, all the character spaces except colons (":")
 *
 *    may be filled with blank characters, or else the Interoperability field may be
 *
 *    filled with blank characters.
 *
 *    The character string length is 20 bytes including NULL for termination.
 *
 *    When the field is left blank, it is treated as unknown.
 *
 *      Tag = 306 (132.H)
 *
 *      Type = ASCII
 *
 *      Count = 20
 *
 *      Default = none
 *
 *    2. DateTimeOriginal(第二处,拍摄时间)
 *
 *    The date and time when the original image data was generated. For a DSC the
 *
 *    date and time the picture was taken are recorded.
 *
 *    The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
 *
 *    the date and time separated by one blank character [20.H].
 *
 *    When the date and time are unknown, all the character spaces except colons (":")
 *
 *    may be filled with blank characters, or else the Interoperability field may be
 *
 *    filled with blank characters.
 *
 *    The character string length is 20 bytes including NULL for termination.
 *
 *    When the field is left blank, it is treated as unknown.
 *
 *      Tag = 36867 (9003.H)
 *
 *      Type = ASCII
 *
 *      Count = 20
 *
 *      Default = none
 *
 *    3. DateTimeDigitized(第三处,存储时间)
 *
 *    The date and time when the image was stored as digital data. If, for example,
 *
 *    an image was captured by DSC and at the same time the file was recorded, then
 *
 *    the DateTimeOriginal and DateTimeDigitized will have the same contents.
 *
 *    The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
 *
 *    the date and time separated by one blank character [20.H].
 *
 *    When the date and time are unknown, all the character spaces except colons (":")
 *
 *    may be filled with blank characters, or else the Interoperability field may be
 *
 *    filled with blank characters.
 *
 *    The character string length is 20 bytes including NULL for termination.
 *
 *    When the field is left blank, it is treated as unknown.
 *
 *      Tag = 36868 (9004.H)
 *
 *      Type = ASCII
 *
 *      Count = 20
 *
 *      Default = none
 *
 * 3、特别的(Special)相机,如富士系列FUJIFILM,使用XML格式记录EXIF,时间格式如下:
 *
 *    <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>
 *
 *    对比正常的(Normal)相片,我们发现两者格式很类似:
 *
 *    2006:12:24 12:33:08   Normal
 *
 *    2006-12-24T12:33:08   Special
 *
 *
 * 另外:
 *
 * 1、由于本人测试的*.tif和*.tiff图片是由*.jpg通过ACDSee转换的,所以可能不准。
 *
 * 2、当然,网上有现成的包可供利用,详细方法请自行搜索,以下是包下载地址:
 *
 *   
http://www.drewnoakes.com/code/exif/releases/metadata-extractor-2.2.0.jar
 *
 * 3、此例没有按照标准的Java规范格式化。
 *
 * 4、开源的目的只有一个:我为人人,人人为我,欢迎开源!
 *
 *
 * Version: 1.00
 *
 * Author: NeedJava
 *
 * E-Mail:
NeedJava@126.com
 *
 * Modified: 2007.08.16/2007.08.29/2007.09.28
 *
 *
 * 你可以使用此程序于任何地方,但请保留程序作者及注释的完整。如果你改进了程序,
 *
 * 请在原作者后添加姓名,如:Author: NeedJava/Jack/Mike,版本及修改时间同理。
 *
 ******************************************************************************/
public final class Rename2PictrueOriginalDateTime
{
  private static char PRI_SEPARATOR = '-';  //主要分隔符

  private static char SUB_SEPARATOR = ' ';  //次要分隔符

  private long totalPictures;    //图片总数

  private long parsedPictures;   //含有有效时间的图片总数

  private long renamedPictures;  //成功修改名称的图片总数

  private long minimumSize;      //处理图片的最小字节数


  /*****************************************************************************
   *
   * 构造函数,默认使用当前路径,不搜索100KB以下图片
   *
   ****************************************************************************/
  public Rename2PictrueOriginalDateTime()
  {
    this( ".", 102400L );
  }

  public Rename2PictrueOriginalDateTime( String fileName )
  {
    this( fileName, 102400L );
  }

  public Rename2PictrueOriginalDateTime( long minimumSize )
  {
    this( ".", minimumSize );
  }

  public Rename2PictrueOriginalDateTime( String fileName, long minimumSize )
  {
    this.totalPictures   = 0L;

    this.parsedPictures  = 0L;

    this.renamedPictures = 0L;

    this.minimumSize     = minimumSize;

    this.listPictures( null, ( fileName==null ? "." : fileName ) );
  }


  /*****************************************************************************
   *
   * 列出当前目录下的文件列表,包括文件和文件夹
   *
   * Windows操作系统中,File类中关键是抽象类FileSystem,而FileSystem关键如下:
   *
   * public static native FileSystem getFileSystem();
   *
   * 实际返回的是子类Win32FileSystem
   *
   ****************************************************************************/
  private final void listPictures( File path, String fileName )
  {
    File file=new File( path, fileName );

    if( file.isDirectory() )
      {
        //得到当前目录下的文件列表,包括文件和文件夹
        String[] children=file.list();

        //如果子集为空,就放弃后面的操作
        if( children==null )
          {
            return;
          }

        //排序
        java.util.Arrays.sort( children );

        //如果子集不为空,则显示
        for( int i=0; i<children.length; i++ )
           {
             listPictures( file, children[i] );
           }
      }
    else if( file.isFile() )
           {
             String suffix=getPictureSuffix( file.getPath() );

             //当前文件是图片
             if( suffix.length()>3 )
               {
                 //图片总数增加
                 setTotalPictures();

                 logger( "/r/nProcess/t["+file.getPath()+"]", true );

                 String datetime=getPictureDateTime( file );

                 if( datetime.length()==19 )  //去掉这行,就可以按序列号重新排序命名
                   {
                     //解析出时间的图片总数增加
                     setParsedPictures();

                     //检查新文件名是否被占用,如果没被占用,就修改名称
                     checkAndRename( file, file.getParent()+File.separatorChar, file.getName(), datetime, suffix, 0 );
                   }
               }
           }
  }


  /*****************************************************************************
   *
   * 根据后缀名判断是否是有效的图片,并且返回小写的后缀名
   *
   * lastIndexOf()和substring()可以完成,但是我还想把后缀名小写,并且减少无谓循环
   *
   ****************************************************************************/
  private final String getPictureSuffix( String fileName )
  {
    if( fileName==null )
      {
        return "";
      }

    int pointer=fileName.length()-1;

    //可能存在“.jpg”这样的文件,即文件名只有4个字符
    if( pointer>2 )
      {
        char c=fileName.charAt( pointer-- );

        if( c=='g'||c=='G' )  //1
          {
            c=fileName.charAt( pointer-- );

            if( c=='p'||c=='P' )  //2
              {
                c=fileName.charAt( pointer-- );

                if( ( c=='j'||c=='J' )&&( pointer>-1 ) )  //3
                  {
                    c=fileName.charAt( pointer );

                    if( c=='.' )  //4
                      {
                        return ".jpg";
                      }
                  }
              }
            else if( c=='e'||c=='E' )  //2
                   {
                     c=fileName.charAt( pointer-- );

                     if( c=='p'||c=='P' )  //3
                       {
                         c=fileName.charAt( pointer-- );

                         if( ( c=='j'||c=='J' )&&( pointer>-1 ) )  //4
                           {
                             c=fileName.charAt( pointer );

                             if( c=='.' )  //5
                               {
                                 return ".jpeg";
                               }
                           }
                       }
                   }
          }
        else if( c=='e'||c=='E' )  //1
               {
                 c=fileName.charAt( pointer-- );

                 if( c=='p'||c=='P' )  //2
                   {
                     c=fileName.charAt( pointer-- );

                     if( ( c=='j'||c=='J' )&&( pointer>-1 ) )  //3
                       {
                         c=fileName.charAt( pointer );

                         if( c=='.' )  //4
                           {
                             return ".jpe";
                           }
                       }
                   }
               }
        else if( c=='f'||c=='F' )  //1
               {
                 c=fileName.charAt( pointer-- );

                 if( c=='i'||c=='I' )  //2
                   {
                     c=fileName.charAt( pointer-- );

                     if( c=='f'||c=='F' )  //3
                       {
                         c=fileName.charAt( pointer-- );

                         if( ( c=='j'||c=='J' )&&( pointer>-1 ) )  //4
                           {
                             c=fileName.charAt( pointer );

                             if( c=='.' )  //5
                               {
                                 return ".jfif";
                               }
                           }
                       }
                     else if( ( c=='t'||c=='T' )&&( pointer>-1 ) )  //3
                            {
                              c=fileName.charAt( pointer );

                              if( c=='.' )  //4
                                {
                                  return ".tif";
                                }
                            }
                   }
                 else if( c=='f'||c=='F' )  //2
                        {
                          c=fileName.charAt( pointer-- );

                          if( c=='i'||c=='I' )  //3
                            {
                              c=fileName.charAt( pointer-- );

                              if( ( c=='t'||c=='T' )&&( pointer>-1 ) )  //4
                                {
                                  c=fileName.charAt( pointer );

                                  if( c=='.' )  //5
                                    {
                                      return ".tiff";
                                    }
                                }
                            }
                        }
               }
      }

    return "";
  }


  /*****************************************************************************
   *
   * 解析出图片中存储的照相时间
   *
   *
   * 正常相片(Normal),时间格式如下:
   *
   * 2001:01:02 12:23:56[NULL]2001:01:02 12:23:56
   *
   * 一般都是400到800字节之间,极个别在200和1500左右
   *
   * 还有些相机(如HP PhotoSmart R607)竟然在3100左右
   *
   *
   * 特殊相片(Special),如富士系列相片FUJIFILM,时间格式如下:
   *
   * <exif:DateTimeOriginal>2006-12-24T13:55:42+08:00</exif:DateTimeOriginal>
   *
   * 一般在8000以内任意地方,非常臃长
   *
   *
   * 综上考虑,我不得不用10240来代替原来的2048
   *
   * 或者我可以使用分段方法,将出现最多的段放在前面,最少的段放后面,我需要统计
   *
   * 现在我遇到的最大的为16000,也就是从2500到16000都有,很少,所以忽略了
   *
   ****************************************************************************/
  private final String getPictureDateTime( File file )
  {
    try{ FileInputStream fis=new FileInputStream( file );

         int fileLength=fis.available();

         ///////////////////////////////////////////////////////////////////////
         //
         // 由ACDSee剪裁生成的图片,仍然保留着详细的EXIF信息,哪怕图片只有一个像素大小,
         //
         // 但是这样的图片有意义吗?我觉得既然是数码相片,至少应该大于100KB。
         //
         // 当图片大小小于一定值时不予理会,当然你可以取消这样的限制
         //
         ///////////////////////////////////////////////////////////////////////
         if( fileLength<minimumSize )
           {
             //及时关闭
             fis.close();

             logger( "Less than "+minimumSize+" bytes, Ignore.", false );

             return "";
           }

         ///////////////////////////////////////////////////////////////////////
         //
         // 时间信息全在文件前10240字节内,我们一次读入,一个一个字节分析,
         //
         // 但是当需要读入的内容大于10240字节时,最好分批读入,每次2048或1024
         //
         ///////////////////////////////////////////////////////////////////////
         byte[] buffer=new byte[10240];

         //为防止溢出,减去240
         int readLength=fis.read( buffer )-240;

         //及时关闭
         fis.close();

         if( readLength>0&&readLength<buffer.length )
           {
             ///////////////////////////////////////////////////////////////////
             //
             // 为速度,不准备转换成char,直接比较数字,如下:
             //
             //  NULL    0
             //
             //  -       45
             //
             //  0       48
             //  1       49
             //  2       50
             //  3       51
             //  4       52
             //  5       53
             //  6       54
             //  7       55
             //  8       56
             //  9       57
             //
             //  :       58
             //
             //  空格    32
             //
             //  T       84
             //  t       116
             //
             //  D       68
             //  d       100
             //
             //  O       79
             //  o       111
             //
             ///////////////////////////////////////////////////////////////////

             //找到有效时间的次数,我们使用第二次找到的时间
             int times=0;

             //为防止溢出,而且没必要搜索最初的100字节
             int n=100;

             //从当前位置向后偏移18,就是时间的最后一位,判断字符是否符合要求
             int offset18;

             while( n<readLength )
                  {
                    offset18=n+18;

                    //末尾是数字
                    if( buffer[offset18]>47&&buffer[offset18]<58 )
                      {
                        //必须是“19”或“20”开头,并且时钟与分钟、分钟与秒钟之间是“:”
                        if( ( buffer[n]==50&&buffer[n+1]==48||buffer[n]==49&&buffer[n+1]==57 )
                          &&( buffer[n+16]==58 )
                          &&( buffer[n+13]==58 ) )
                          {
                            //日期与时间分隔的是空格“ ”,并且年与月、月与日之间是“:”,也就是2006:06:06 06:06:06
                            if( buffer[n+10]==32&&buffer[n+7]==58&&buffer[n+4]==58 )
                              {
                                times++;

                                //Normal,两个时间在一起,或是第二次找到的时间
                                if( ( buffer[n+36]==58&&buffer[n+33]==58&&buffer[n+30]==32&&buffer[n+27]==58&&buffer[n+24]==58 )
                                  ||( times==2 ) )
                                  {
                                    return parseDateTime( buffer, n, 19 );
                                  }
                              }
                            //日期与时间分隔的是“T”或“t”,并且年与月、月与日之间是“-”,也就是2006-06-06T06:06:06
                            else if( ( buffer[n+10]==84||buffer[n+10]==116 )
                                   &&( buffer[n+7]==45 )
                                   &&( buffer[n+4]==45 ) )
                                   {
                                     times++;

                                     //Special,含有“DateTimeOriginal”,只判断“D”或“d”、“T”或“t”、“O”或“o”三个字符
                                     if( ( buffer[n-9]==79||buffer[n-9]==111 )
                                       &&( buffer[n-13]==84||buffer[n-13]==116 )
                                       &&( buffer[n-17]==68||buffer[n-17]==100 ) )
                                       {
                                         return parseDateTime( buffer, n, 19 );
                                       }
                                   }
                          }

                        //别忘了移位
                        n++;
                      }
                    //末尾是“:”,向后移动2位
                    else if( buffer[offset18]==58 )
                           {
                             /////////////////////////////////////////////////////
                             //
                             // [     CANON  42  H        2006:12:24 12:33:08 2006:12:24 12:33:08     ]
                             //                                        |
                             // [  <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>]
                             //                                        |
                             //                      0000:00:00 00:00:0A
                             //                                        |
                             //                      0000-00-00T00:00:0A
                             //                                        |
                             //                        0000:00:00 00:00:0A
                             //                                        |
                             //                        0000-00-00T00:00:0A
                             //
                             /////////////////////////////////////////////////////
                             n+=2;
                           }
                    //末尾是空格“ ”、“T”、“t”,向后移动8位
                    else if( buffer[offset18]==32||buffer[offset18]==84||buffer[offset18]==116 )
                           {
                             /////////////////////////////////////////////////////
                             //
                             // [     CANON  42  H        2006:12:24 12:33:08 2006:12:24 12:33:08     ]
                             //                                     |
                             // [  <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>]
                             //                                     |
                             //                   0000:00:00 00:00:0A
                             //                                     |
                             //                   0000-00-00T00:00:0A
                             //                                     |
                             //                           0000:00:00 00:00:0A
                             //                                     |
                             //                           0000-00-00T00:00:0A
                             //
                             /////////////////////////////////////////////////////
                             n+=8;
                           }
                    //末尾是“-”,向后移动11位
                    else if( buffer[offset18]==45 )
                           {
                             /////////////////////////////////////////////////////
                             //
                             // [  <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>]
                             //                               |
                             //             0000-00-00T00:00:0A
                             //                               |
                             //                        0000-00-00T00:00:0A
                             //
                             /////////////////////////////////////////////////////
                             n+=11;
                           }
                         else{ //末尾不包含以上任何字符,整块向后移动19位

                               ///////////////////////////////////////////////////
                               //
                               // [      CANON  42  H        2   f light 24 F       55       ]
                               //                                |                  |
                               //              0000-00-00T00:00:0A                  |
                               //                                                   |
                               //                                 0000-00-00T00:00:0A
                               //
                               ///////////////////////////////////////////////////
                               n+=19;
                             }
                  }
           }
       }
    catch( FileNotFoundException fnfe )
         {
           fnfe.printStackTrace();
         }
    catch( IOException ioe )
         {
           ioe.printStackTrace();
         }
    catch( Exception e )
         {
           e.printStackTrace();
         }

    return "";
  }


  /*****************************************************************************
   *
   * 将已经定位好的日期时间提取出来
   *
   ****************************************************************************/
  private final String parseDateTime( byte[] buffer, int offset, int length )
  {
    if( ( buffer!=null )&&( offset>-1&&offset<buffer.length )&&( length>0&&length<buffer.length ) )
      {
        char[] parse=new char[length];

        byte b;

        for( int i=0; i<length; i++ )
           {
             b=buffer[offset+i];

             if( b>=48&&b<=57 )  //数字,没有检查日期合法性
               {
                 parse[i]=(char)b;  //由于此处始终大于零,所以不用考虑byte的正负符号位
               }
             else if( b==58 )  //由于“:”不能用于文件名,我们用“-”代替
                    {
                      parse[i]=this.PRI_SEPARATOR;
                    }
                  else{ parse[i]=this.SUB_SEPARATOR;  //NULL值或其他非数值用空格代替
                      }
           }

        return new String( parse );
      }

    return "";
  }


  /*****************************************************************************
   *
   * 检查新文件名称是否已被占用,如果没被占用,则修改名称
   *
   * Some bug here.
   *
   ****************************************************************************/
  private final void checkAndRename( File file, String path, String oldName, String prefix, String suffix, int number )
  {
    if( file!=null&&path!=null&&oldName!=null&&prefix!=null&&suffix!=null&&number>-1 )
      {
        String newName=( number>0 ? prefix+this.SUB_SEPARATOR+getNumberSequence( number )+suffix : prefix+suffix );

        //如果图片已经改好了,不需要再次修改
        if( newName.equals( oldName ) )
          {
            logger( "Rename/t["+newName+"]/tNo Need", false );

            return;
          }

        File newFile=new File( path+newName );

        if( newFile.exists() )  //已经存在同名但本质不同的图片
          {
            checkAndRename( file, path, oldName, prefix, suffix, number+1 );
          }
        else{ if( file.renameTo( newFile ) )
                {
                  //修改名称成功的图片总数增加
                  setRenamedPictures();

                  logger( "Rename/t["+newName+"]/tSucceed", false );
                }
              else{ logger( "Rename/t["+newName+"]/tFailed", false );
                  }
            }
      }
  }


  /*****************************************************************************
   *
   * 得到诸如001、002、012、569、999、0102、1345、4567、56789这样的数字序列
   *
   * 从1000开始递增,当小于2000时,提取千位后面的三位,组成000到999的数字序列
   *
   * 当递增大于等于2000时,取其减去1000的值,组成1000到99999的数字序列
   *
   ****************************************************************************/
  private final String getNumberSequence( int number )
  {
    if( number>-1&&number<100000 )  //十万左右的图片放一个文件夹?
      {
        int temp=number+1000;

        char[] buffer=new char[7];  //7在此足够了

        int pointer=6;  //buffer.length-1=7-1=6

        while( temp>0 )
             {
               buffer[pointer--]=(char)( temp%10+48 );  //48是'0'的ASCII码

               temp/=10;

               if( pointer==3 )  //到千位了(7-4=3),此时需要把人为增加的1000减去
                 {
                   temp--;
                 }
             }

        pointer++;

        return new String( buffer, pointer, 7-pointer );  //7为buffer的长度
      }

    return "";
  }


  /*****************************************************************************
   *
   * 总共的图片数,无须考虑同步
   *
   ****************************************************************************/
  private final void setTotalPictures()
  {
    this.totalPictures++;
  }

  public final long getTotalPictures()
  {
    return this.totalPictures;
  }

  /*****************************************************************************
   *
   * 解析出时间的图片数,无须考虑同步
   *
   ****************************************************************************/
  private final void setParsedPictures()
  {
    this.parsedPictures++;
  }

  public final long getParsedPictures()
  {
    return this.parsedPictures;
  }

  /*****************************************************************************
   *
   * 改名成功的图片数,无须考虑同步
   *
   ****************************************************************************/
  private final void setRenamedPictures()
  {
    this.renamedPictures++;
  }

  public final long getRenamedPictures()
  {
    return this.renamedPictures;
  }


  /*****************************************************************************
   *
   * 既向控制台显示,又向日志写入
   *
   ****************************************************************************/
  private final static void logger( String message, boolean both )
  {
    if( message!=null )
      {
        if( both )
          {
            System.out.println( message );
          }

        System.err.println( message );
      }
  }


  /*****************************************************************************
   *
   * 主函数入口
   *
   ****************************************************************************/
  public static void main( String[] args )
  {
    try{ //标准错误输出重新定向到日志文件
         System.setErr( new PrintStream( new FileOutputStream( "log.txt" ) ) );

         //程序总耗时统计
         long begin=System.currentTimeMillis();

         Rename2PictrueOriginalDateTime rpodt=new Rename2PictrueOriginalDateTime();

         logger( "/r/n共有图片:"+( rpodt.getTotalPictures() )+"张", true );
         logger( "/r/n有效图片:"+( rpodt.getParsedPictures() )+"张", true );
         logger( "/r/n修改成功:"+( rpodt.getRenamedPictures() )+"张", true );
         logger( "/r/n修改失败:"+( rpodt.getParsedPictures()-rpodt.getRenamedPictures() )+"张", true );

         logger( "/r/n总共耗时:"+( System.currentTimeMillis()-begin )+"毫秒", true );
       }
    catch( FileNotFoundException fnfe )
         {
           fnfe.printStackTrace();
         }
    catch( IOException ioe )
         {
           ioe.printStackTrace();
         }
    catch( Exception e )
         {
           e.printStackTrace();
         }
  }
}

 

 

///////////////////////////////////////////////////////////////////////////////

 

以下是最新版本,修改了一些Bug,优化了速度:

 

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;


/*******************************************************************************
 *
 * 读出数码图片中的拍照时间
 *
 *
 * 原理:
 *
 * 1、由于数码图片的拍照时间可以直接从图片中搜索到,所以本例不需要分析EXIF的格式。
 *
 * 2、正常的(Normal)数码图片,会有三处到四处的时间,其中第二、第三处固定在一起,
 *
 *    第二处是图片拍摄时间,第三处是图片存储时间,一般两者相同,他们之间用NULL值
 *
 *    分隔(ASCII值为0),如下:
 *
 *    2001:01:02 12:23:56[NULL]2001:01:02 12:23:56[NULL]
 *
 *    两者位置不定,但格式好查找,八个冒号,两个空格,两个NULL值,其余为数字。
 *
 *    不用考虑01:09:34被压缩为1:9:34这样的特例,见EXIF2.1规范关于时间的三段:
 *
 *    1. DateTime(第一处,修改时间)
 *
 *    The date and time of image creation. In this standard it is the date and time
 *
 *    the file was changed.
 *
 *    The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
 *
 *    the date and time separated by one blank character [20.H].
 *
 *    When the date and time are unknown, all the character spaces except colons (":")
 *
 *    may be filled with blank characters, or else the Interoperability field may be
 *
 *    filled with blank characters.
 *
 *    The character string length is 20 bytes including NULL for termination.
 *
 *    When the field is left blank, it is treated as unknown.
 *
 *      Tag = 306 (132.H)
 *
 *      Type = ASCII
 *
 *      Count = 20
 *
 *      Default = none
 *
 *    2. DateTimeOriginal(第二处,拍摄时间)
 *
 *    The date and time when the original image data was generated. For a DSC the
 *
 *    date and time the picture was taken are recorded.
 *
 *    The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
 *
 *    the date and time separated by one blank character [20.H].
 *
 *    When the date and time are unknown, all the character spaces except colons (":")
 *
 *    may be filled with blank characters, or else the Interoperability field may be
 *
 *    filled with blank characters.
 *
 *    The character string length is 20 bytes including NULL for termination.
 *
 *    When the field is left blank, it is treated as unknown.
 *
 *      Tag = 36867 (9003.H)
 *
 *      Type = ASCII
 *
 *      Count = 20
 *
 *      Default = none
 *
 *    3. DateTimeDigitized(第三处,存储时间)
 *
 *    The date and time when the image was stored as digital data. If, for example,
 *
 *    an image was captured by DSC and at the same time the file was recorded, then
 *
 *    the DateTimeOriginal and DateTimeDigitized will have the same contents.
 *
 *    The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
 *
 *    the date and time separated by one blank character [20.H].
 *
 *    When the date and time are unknown, all the character spaces except colons (":")
 *
 *    may be filled with blank characters, or else the Interoperability field may be
 *
 *    filled with blank characters.
 *
 *    The character string length is 20 bytes including NULL for termination.
 *
 *    When the field is left blank, it is treated as unknown.
 *
 *      Tag = 36868 (9004.H)
 *
 *      Type = ASCII
 *
 *      Count = 20
 *
 *      Default = none
 *
 * 3、特别的(Special)相机,如富士系列FUJIFILM,使用XML格式记录EXIF,时间格式如下:
 *
 *    <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>
 *
 *    对比正常的(Normal)相片,我们发现两者格式很类似:
 *
 *    2006:12:24 12:33:08   Normal
 *
 *    2006-12-24T12:33:08   Special
 *
 *
 * 另外:
 *
 * 1、由于本人测试的*.tif和*.tiff图片是由*.jpg通过ACDSee转换的,所以可能不准。
 *
 * 2、当然,网上有现成的包可供利用,详细方法请自行搜索,以下是包下载地址:
 *
 *    http://www.drewnoakes.com/code/exif/releases/metadata-extractor-2.2.0.jar
 *
 * 3、此例没有按照标准的Java规范格式化。
 *
 * 4、开源的目的只有一个:我为人人,人人为我,欢迎开源!
 *
 *
 * Version: 1.10
 *
 * Author: NeedJava
 *
 * E-Mail: NeedJava@126.com
 *
 * Modified: 2007.08.16/2007.08.29/2007.09.28/2010.03.15
 *
 *
 * 你可以使用此程序于任何地方,但请保留程序作者及注释的完整。如果你改进了程序,
 *
 * 请在原作者后添加姓名,如:Author: NeedJava/Jack/Mike,版本及修改时间同理。
 *
 ******************************************************************************/
public final class PictureRenamer
{
    public static final int FILE_MIN_LENGTH = 102400;  //查找文件的最小字节数

    public static final int SEQUENCE_LENGTH = 3;  //默认图片序列号的长度

    private static final char[] SUFFIX_JPG  = { '.', 'j', 'p', 'g' };  //{ 46, 106, 112, 103 }

    private static final char[] SUFFIX_JPEG = { '.', 'j', 'p', 'e', 'g' };  //{ 46, 106, 112, 101, 103 }

    private static final char[] SUFFIX_JPE  = { '.', 'j', 'p', 'e' };  //{ 46, 106, 112, 101 }

    private static final char[] SUFFIX_JFIF = { '.', 'j', 'f', 'i', 'f' };  //{ 46, 106, 102, 105, 102 }

    private static final char[] SUFFIX_TIF  = { '.', 't', 'i', 'f' };  //{ 46, 116, 105, 102 }

    private static final char[] SUFFIX_TIFF = { '.', 't', 'i', 'f', 'f' };  //{ 46, 116, 105, 102, 102 }

    private static final char PRI_SEPARATOR = '-';  //45 主要分隔符

    private static final char SUB_SEPARATOR = ' ';  //32 次要分隔符

    private int minLength;  //处理图片的最小字节数

    private int sequenceLength;  //图片序列号的长度

    private int totalFolders;  //文件夹总数

    private int totalFiles;  //文件总数

    private int totalPictures;  //图片总数

    private int parsedPictures;  //含有有效时间的图片总数

    private int renamedPictures;  //成功修改名称的图片总数

    /***************************************************************************
     *
     * 构造函数,默认使用当前路径,不搜索100KB以下图片
     *
     * 由ACDSee剪裁生成的图片,仍然保留着详细的EXIF信息,哪怕图片只有一个像素,
     *
     * 但是这样的图片有意义吗?我觉得既然是数码相片,至少应该大于100KB。
     *
     * 当图片大小小于一定值时不予理会,当然你可以取消这样的限制
     *
     **************************************************************************/
    public PictureRenamer(){ this( FILE_MIN_LENGTH, SEQUENCE_LENGTH ); }

    public PictureRenamer( int minLength, int sequenceLength )
    {
        this.totalFolders    = 0;

        this.totalFiles      = 0;

        this.totalPictures   = 0;

        this.parsedPictures  = 0;

        this.renamedPictures = 0;

        this.minLength = ( minLength < 0 ? FILE_MIN_LENGTH : minLength );

        this.sequenceLength = ( sequenceLength < 0 ? SEQUENCE_LENGTH : sequenceLength );
    }

    /***************************************************************************
     *
     * 列出当前目录下的文件列表,包括文件和文件夹
     *
     * Windows操作系统中,File类中关键是抽象类FileSystem,而FileSystem关键如下:
     *
     * public static native FileSystem getFileSystem();
     *
     * 实际返回的是子类Win32FileSystem
     *
     **************************************************************************/
    public final void listPictures( File parent, String fileName ) throws FileNotFoundException, IOException
    {
        File file = new File( parent, fileName );

        if( file.isDirectory() )
        {
            totalFolders ++;

            String[] children = file.list(); if( children == null ){ return; }

            //java.util.Arrays.sort( children );  //没必要排序

            for( int i = 0; i < children.length; i ++ ){ listPictures( file, children[i] ); }
        }
        else
        {
            totalFiles ++;

            char[] suffix = getPictureSuffix( fileName ); if( suffix == null ){ return; }

            if( suffix.length > 0 )  //当前文件是图片
            {
                totalPictures ++;

                //logger( "/r/nProcess/t[" + file.getPath() + "]", false );

                //TODO:增加观察者,代替logger,使用线程wait和notify

                //TODO:判断是否是格式化过的图片,如果是,就退出,或者强制修改。XXXX:放弃这个,因为AcdSee处理的经常是错的

                long length = file.length(); if( length < minLength ){ /*logger( length + " is less than " + minLength + " bytes, Ignore.", false );*/ return; }

                char[] datetime = getPictureDateTime( file ); if( datetime == null ){ return; }  //fileName.substring( 0, fileName.length() - suffix.length ).toCharArray();

                if( datetime.length == 19/**/ )  //注释掉这行,就可以按序列号重新排序命名
                {
                    parsedPictures ++;

                    String newName = rename( parent, file, fileName, datetime, suffix, 0/*-1*/ );  //检查新文件名是否被占用,如果没被占用,就修改名称

                    if( newName == null ){ /*logger( "Rename/t[" + newName + "]/tFailed", false );*/ return; }

                    renamedPictures ++;

                    //logger( "Rename/t[" + newName + "]/tSucceed", false );
                }
            }
        }
    }

    /***************************************************************************
     *
     * 根据后缀名判断是否是有效的图片,并且返回小写的后缀名
     *
     * lastIndexOf()和substring()可以完成,但是我还想把后缀名小写,并且减少无谓循环
     *
     **************************************************************************/
    private final char[] getPictureSuffix( String fileName )
    {
        if( fileName == null ){ return null; }

        int pointer = fileName.length() - 1;

        if( pointer > 2 )  //可能存在“.jpg”这样的文件,即文件名只有4个字符
        {
            char c = fileName.charAt( pointer -- );

            if( c == 'g' || c == 'G' )  //1
            {
                c = fileName.charAt( pointer -- );

                if( c == 'p' || c == 'P' )  //2
                {
                    c = fileName.charAt( pointer -- );

                    if( ( c == 'j' || c == 'J' ) && ( pointer > -1 ) )  //3
                    {
                        if( fileName.charAt( pointer ) == '.' ){ return SUFFIX_JPG; }  //4
                    }
                }
                else if( c == 'e' || c == 'E' )  //2
                {
                    c = fileName.charAt( pointer -- );

                    if( c == 'p' || c == 'P' )  //3
                    {
                        c = fileName.charAt( pointer -- );

                        if( ( c == 'j' || c == 'J' ) && ( pointer > -1 ) )  //4
                        {
                            if( fileName.charAt( pointer ) == '.' ){ return SUFFIX_JPEG; }  //5
                        }
                    }
                }
            }
            else if( c == 'e' || c == 'E' )  //1
            {
                c = fileName.charAt( pointer -- );

                if( c == 'p' || c == 'P' )  //2
                {
                    c = fileName.charAt( pointer -- );

                    if( ( c == 'j' || c == 'J' ) && ( pointer > -1 ) )  //3
                    {
                        if( fileName.charAt( pointer ) == '.' ){ return SUFFIX_JPE; }  //4
                    }
                }
            }
            else if( c == 'f' || c == 'F' )  //1
            {
                c = fileName.charAt( pointer -- );

                if( c == 'i' || c == 'I' )  //2
                {
                    c = fileName.charAt( pointer -- );

                    if( c == 'f' || c == 'F' )  //3
                    {
                        c = fileName.charAt( pointer -- );

                        if( ( c == 'j' || c == 'J' ) && ( pointer > -1 ) )  //4
                        {
                            if( fileName.charAt( pointer ) == '.' ){ return SUFFIX_JFIF; }  //5
                        }
                    }
                    else if( ( c == 't' || c == 'T' ) && ( pointer > -1 ) )  //3
                    {
                        if( fileName.charAt( pointer ) == '.' ){ return SUFFIX_TIF; }  //4
                    }
                }
                else if( c == 'f' || c == 'F' )  //2
                {
                    c = fileName.charAt( pointer -- );

                    if( c == 'i' || c == 'I' )  //3
                    {
                        c = fileName.charAt( pointer -- );

                        if( ( c == 't' || c == 'T' ) && ( pointer > -1 ) )  //4
                        {
                            if( fileName.charAt( pointer ) == '.' ){ return SUFFIX_TIFF; }  //5
                        }
                    }
                }
            }
        }

        return null;
    }

    /***************************************************************************
     *
     * 解析出图片中存储的照相时间
     *
     *
     * 正常相片(Normal),时间格式如下:
     *
     * 2001:01:02 12:23:56[NULL]2001:01:02 12:23:56
     *
     * 一般都是400到800字节之间,极个别在200和1500左右
     *
     * 还有些相机(如HP PhotoSmart R607)竟然在3100左右
     *
     *
     * 特殊相片(Special),如富士系列相片FUJIFILM,时间格式如下:
     *
     * <exif:DateTimeOriginal>2006-12-24T13:55:42+08:00</exif:DateTimeOriginal>
     *
     * 一般在8000以内任意地方,非常臃长
     *
     *
     * 综上考虑,我不得不用10240来代替原来的2048
     *
     * 或者我可以使用分段方法,将出现最多的段放在前面,最少的段放后面,我需要统计
     *
     * 现在我遇到的最大的为16000,也就是从2500到16000都有,很少,所以忽略了
     *
     * 现在已经分段了
     *
     **************************************************************************/
    private final char[] getPictureDateTime( File file ) throws FileNotFoundException, IOException
    {
        FileInputStream fis = new FileInputStream( file );

        ////////////////////////////////////////////////////////////////////////
        //
        // 时间信息全在文件前10240字节内,我们一次读入,一个一个字节分析,
        //
        // 但是当需要读入的内容大于10240字节时,最好分批读入,每次2048或1024
        //
        ////////////////////////////////////////////////////////////////////////
        byte[] buffer = new byte[2048];

        int readLength = 0;

        int remain = 0;

        int n = 128;  //为防止溢出,而且没必要搜索最初的128字节

        int readTimes = 8;  //readTimes和buffer.length的乘积应当在10000至16000左右,保证只搜索图片前16000字节

        int foundTimes = 0;  //找到有效时间的次数,我们使用第二次找到的时间

        int foundOffset = 0;  //在哪找到的

        byte tailByte = 0;  //从当前位置向后偏移18,就是时间的最后一位,判断字符是否符合要求

        while( -- readTimes >= 0 && ( readLength = fis.read( buffer, remain, buffer.length - remain ) + remain ) >= 0 )
        {
            ////////////////////////////////////////////////////////////////////
            //
            // 为速度,不准备转换成char,直接比较数字,如下:
            //
            //  NULL    0
            //
            //  -       45
            //
            //  0       48
            //  1       49
            //  2       50
            //  3       51
            //  4       52
            //  5       53
            //  6       54
            //  7       55
            //  8       56
            //  9       57
            //
            //  :       58
            //
            //  空格    32
            //
            //  T       84
            //  t       116
            //
            //  D       68
            //  d       100
            //
            //  O       79
            //  o       111
            //
            ////////////////////////////////////////////////////////////////////

            while( ( remain = readLength - n ) > 0 )
            {
                if( remain <= 38 && n >= 19 )  //快要到末尾了,把剩余的字节复制到头部,我们重新开始
                {
                    System.arraycopy( buffer, n -= 19, buffer, 0, remain += 19 );

                    foundOffset += n; n = 0; break;
                }

                tailByte = buffer[n + 18];

                //末尾是数字
                if( tailByte > 47 && tailByte < 58 )
                {
                    //必须是数字开头,并且时钟与分钟、分钟与秒钟之间是“:”
                    if( buffer[n] > 47 && buffer[n] < 58 && buffer[n + 16] == 58 && buffer[n + 13] == 58 )
                    {
                        //日期与时间分隔的是空格“ ”,并且年与月、月与日之间是“:”,也就是2006:06:06 06:06:06
                        if( buffer[n + 10] == 32 && buffer[n + 7] == 58 && buffer[n + 4] == 58 )
                        {
                            foundTimes ++;

                            //Normal,两个时间在一起,或是第二次找到的时间
                            if( ( buffer[n + 36] == 58 && buffer[n + 33] == 58 && buffer[n + 30] == 32 && buffer[n + 27] == 58 && buffer[n + 24] == 58 ) || ( foundTimes == 2 ) )
                            {
                                foundOffset += n;

                                //System.err.println( foundOffset );

                                fis.close(); return parseDateTime( buffer, n, 19 );
                            }
                        }

                        //日期与时间分隔的是“T”或“t”,并且年与月、月与日之间是“-”,也就是2006-06-06T06:06:06
                        else if( ( buffer[n + 10] == 84 || buffer[n + 10] == 116 ) && buffer[n + 7] == 45 && buffer[n + 4] == 45 )
                        {
                            foundTimes ++;

                            //Special,含有“DateTimeOriginal”,只判断“D”或“d”、“T”或“t”、“O”或“o”三个字符
                            if( ( buffer[n - 9] == 79 || buffer[n - 9] == 111 ) && ( buffer[n - 13] == 84 || buffer[n - 13] == 116 ) && ( buffer[n - 17] == 68 || buffer[n - 17] == 100 ) )
                            {
                                foundOffset += n;

                                //System.err.println( foundOffset );

                                fis.close(); return parseDateTime( buffer, n, 19 );
                            }
                        }
                    }

                    //别忘了移位
                    n ++;
                }

                //末尾是“:”,向后移动2位
                else if( tailByte == 58 )
                {
                    ////////////////////////////////////////////////////////////
                    //
                    // [     CANON  42  H        2006:12:24 12:33:08 2006:12:24 12:33:08     ]
                    //                                        |
                    // [  <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>]
                    //                                        |
                    //                      0000:00:00 00:00:0A
                    //                                        |
                    //                      0000-00-00T00:00:0A
                    //                                        |
                    //                        0000:00:00 00:00:0A
                    //                                        |
                    //                        0000-00-00T00:00:0A
                    //
                    ////////////////////////////////////////////////////////////
                    n += 2;
                }

                //末尾是空格“ ”、“T”、“t”,向后移动8位
                else if( tailByte == 32 || tailByte == 84 || tailByte == 116 )
                {
                    ////////////////////////////////////////////////////////////
                    //
                    // [     CANON  42  H        2006:12:24 12:33:08 2006:12:24 12:33:08     ]
                    //                                     |
                    // [  <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>]
                    //                                     |
                    //                   0000:00:00 00:00:0A
                    //                                     |
                    //                   0000-00-00T00:00:0A
                    //                                     |
                    //                           0000:00:00 00:00:0A
                    //                                     |
                    //                           0000-00-00T00:00:0A
                    //
                    ////////////////////////////////////////////////////////////
                    n += 8;
                }

                //末尾是“-”,向后移动11位
                else if( tailByte == 45 )
                {
                    ////////////////////////////////////////////////////////////
                    //
                    // [  <exif:DateTimeOriginal>2006-12-24T12:33:08+08:00</exif:DateTimeOriginal>]
                    //                               |
                    //             0000-00-00T00:00:0A
                    //                               |
                    //                        0000-00-00T00:00:0A
                    //
                    ////////////////////////////////////////////////////////////
                    n += 11;
                }

                //末尾不包含以上任何字符,整块向后移动19位
                else
                {
                    ////////////////////////////////////////////////////////////
                    //
                    // [      CANON  42  H        2   f light 24 F       55       ]
                    //                                |                  |
                    //              0000-00-00T00:00:0A                  |
                    //                                                   |
                    //                                 0000-00-00T00:00:0A
                    //
                    ////////////////////////////////////////////////////////////
                    n += 19;
                }
            }
        }

        fis.close(); return null;
    }

    /***************************************************************************
     *
     * 将已经定位好的日期时间提取出来
     *
     **************************************************************************/
    private final char[] parseDateTime( byte[] buf, int off, int len )
    {
        if( buf == null || off < 0 || len < 0 || off + 1 > buf.length || off + len > buf.length ){ return null; }

        char[] array = new char[len];

        byte b;

        for( int i = 0; i < len; i ++ )
        {
            b = buf[off + i];

            if( b >= 48/*0*/ && b <= 57/*9*/ ){ array[i] = (char)b; }  //数字,没有检查日期合法性

            else if( b == 58/*:*/ ){ array[i] = PRI_SEPARATOR; }  //由于“:”不能用于文件名,我们用“-”代替

            else{ array[i] = SUB_SEPARATOR; }  //NULL值或其他非数值用空格代替
        }

        return array;
    }

    /***************************************************************************
     *
     * 检查新文件名称是否已被占用,如果没被占用,则修改名称
     *
     **************************************************************************/
    private final String rename( File parent, File file, String name, char[] prefix, char[] suffix, int number )
    {
        if( parent == null || file == null || prefix == null || suffix == null ){ return null; }

        char[] array = new char[64/**/];

        ////////////////////////////////////////////////////////////////////////

        int pointer = array.length - suffix.length;

        System.arraycopy( suffix, 0, array, pointer, suffix.length );  //[                       .jpg]

        if( number > 0/*-1*/ )
        {
            pointer = writeNumberSequence( array, -- pointer, number );  //[                  001.jpg]

            array[pointer] = SUB_SEPARATOR/**/;  //[                   _001.jpg]
        }

        int temp = pointer = pointer - prefix.length;

        System.arraycopy( prefix, 0, array, pointer, prefix.length );  //[2008-01-01 01-01-01_001.jpg]

        //System.out.println( "Get new file name: " + new String( array, pointer, array.length - pointer ) );

        ////////////////////////////////////////////////////////////////////////

        if( array.length - temp == name.length() )
        {
            for( int i = 0; temp < array.length; temp ++, i ++ )
            {
                //从pointer的点开始字符比较

                if( array[temp] != name.charAt( i ) ){ break; }
            }
        }

        if( temp == array.length ){ return null/**/; }  //如果图片已经改好了,不需要再次修改

        ////////////////////////////////////////////////////////////////////////

        String newName = new String( array, pointer, array.length - pointer );

        File newFile = new File( parent, newName );

        if( newFile.exists() ){ return rename( parent, file, name, prefix, suffix, number + 1 ); }  //已经存在同名但本质不同的图片

        else if( file.renameTo( newFile ) ){ return newName; }  //改名成功,测试发现renameTo很耗时间

        return null;
    }

    /***************************************************************************
     *
     * 得到诸如001、002、012、569、999、0102、1345、4567、56789这样的数字序列
     *
     **************************************************************************/
    private final int writeNumberSequence( char[] array, int offset, int number )
    {
        if( array == null || offset < 0 || number < 0 ){ return offset; }

        int i = 0, pointer = offset, temp = number;

        for( ; i < sequenceLength; i ++, temp /= 10 )
        {
            array[pointer --] = (char)( temp % 10 + 48 );  //48是'0'的ASCII码
        }

        for( ; temp > 0; temp /= 10 )
        {
            array[pointer --] = (char)( temp % 10 + 48 );  //48是'0'的ASCII码
        }

        return pointer;
    }

    public final int getTotalFolders(){ return totalFolders; }

    public final int getTotalFiles(){ return totalFiles; }

    public final int getTotalPictures(){ return totalPictures; }

    public final int getParsedPictures(){ return parsedPictures; }

    public final int getRenamedPictures(){ return renamedPictures; }

    /***************************************************************************
     *
     * 既向控制台显示,又向日志写入
     *
     **************************************************************************/
    private final static void logger( String message, boolean both )
    {
        if( message == null || message.length() < 1 ){ return; }

        if( both ){ System.out.println( message ); }

        System.err.println( message );
    }

    public static void main( String[] args )
    {
        try
        {
            System.setErr( new PrintStream( new FileOutputStream( "log.txt" ) ) );

            long start = System.currentTimeMillis();

            PictureRenamer rpodt = new PictureRenamer( 10240, 3 );

            rpodt.listPictures( null, "." );

            logger( "/r/n共有文件夹:" + ( rpodt.getTotalFolders() ) + "个", true );

            logger( "/r/n共有文件:" + ( rpodt.getTotalFiles() ) + "个", true );

            logger( "/r/n共有图片:" + ( rpodt.getTotalPictures() ) + "张", true );

            logger( "/r/n有效图片:" + ( rpodt.getParsedPictures() ) + "张", true );

            logger( "/r/n修改成功:" + ( rpodt.getRenamedPictures() ) + "张", true );

            logger( "/r/n修改失败:" + ( rpodt.getParsedPictures() - rpodt.getRenamedPictures() ) + "张", true );

            logger( "/r/n总共耗时:" + ( System.currentTimeMillis() - start ) + "毫秒", true );
        }
        catch( FileNotFoundException fnfe ){ fnfe.printStackTrace(); }

        catch( IOException ioe ){ ioe.printStackTrace(); }

        catch( Exception e ){ e.printStackTrace(); }
    }
}

 

 

根据文件修改时间批量重命名文件 根据照片的拍摄日期(没有拍摄日期则取最后修改时间)或者任意文件的最后修改时间重命名文件。例:原文件名 IMG_123.JPG 重命名之后20150427_162001_IMG_123.JPG 立即下载

相关推荐

批量照片重命名V1.2.0.0|按照片Exif中的拍摄时间日期

按一DX的要求特制的程序。 例如照片“12345.jpg”,重命名后是“2007-11-17 18-41-44.jpg”。 如果按预设格式会产生同名文件,则程序自动添加#???后缀,例如“西安 2007-11-17 #008.jpg”。 文件名格式可以自定义。 1.2.0.0 需要.NET 2.0环境支持。

java实现读取图片exif数据(如拍摄时间,经纬度等)

我们需要添加一个依赖 <!-- https://mvnrepository.com/artifact/com.drewnoakes/metadata-extractor --> <dependency> <groupId>com.drewnoakes</groupId> <a...

matthew_leung的博客 4306

根据图片的exif时间信息-重命名jpg文件

NULL 博文链接:https://fantasycodecat.iteye.com/blog/913933

使用Java读取和修改图片的Exif信息

可交换图像文件格式(英语:Exchangeable image file format,官方简称Exif),是专门为数码相机的照片设定的,可以记录数码照片的属性信息和拍摄数据。使用Java读取和修改图片的Exif信息。使用Java复制图片的Exif信息

gallonyin的博客 4111

java实现批量更改照片的名字

使用java语言实现批量更改照片的名字,使得这些照片的名字按照一定的规律命名。

Java读取照片地址、GPS信息、定位照片精确位置完整项目【附测试照片一张】.zip

java对照片进行定位 获取拍摄时间、拍摄地点、拍摄手机型号、像素比例、gps信息、海拔等等完整项目

java根据图片创建日期,或最后修改日期重命名

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import jav...

weixin_30847939的博客 1064

因果推断--PSM的原理和应用(二)

上一篇介绍了DID,本文介绍和DID可一起搭配使用的一种因果推断方法PSM。在正式介绍PSM之前,先来简单回顾一下为什么需要因果推断以及如何做因果推断。我们都知道相关非因果,比起相关我们更希望知道两个事件之间的因果关系,有了确切的因果关系,才能知道对A如何操作才能引起B的变化。解决因果推断问题,目前主要有两种框架,Rubin虚拟事实模型和Pearl因果图模型。站在数据分析的角度上,Rubin虚拟事实模型更容易理解,其核心思想是寻找恰当的对照组。

baidu_26137595的博客 1万+

当Metadata失效时:我是如何从2000张手机自拍照片里“考古“出真实拍摄时间的?

而对于如何识别图片的拍摄信息呢?这里有一个Java库:metadata-extractor,它用于从媒体文件中提取元数据。它支持多种格式的元数据,包括EXIF、IPTC、XMP、ICC以及其他可能在单个图像中存在的元数据格式。这个库可以处理多种类型的文件,包括JPEG、TIFF、WebP、WAV、PSD、PNG、BMP、GIF、HEIF (HEIC & AVIF)、ICO、PCX、QuickTime、MP4、Camera Raw等。

Apple_Boy的博客 1253

sklearn2pmml xgboost缺失值(missing)处理的坑

sklearn2pmml xgboost缺失值(missing)如何处理 今天同事在部署xgboost pmml模型时遇到了大坑,线上spark预测和本地python预测结果怎么都不对应,记录一下处理过程。 看了下同事的代码,貌似也没有问题 from sklearn2pmml import PMMLPipeline from sklearn2pmml import sklearn2pmml fro...

Skycrab 8975

5分钟搞定:用Pyannote和Whisper实现带说话人分离的语音转文字(附完整代码)

本文详细介绍了如何快速构建一个集成了说话人分离功能的语音转文字系统。通过结合OpenAI的Whisper模型进行高精度语音识别和Pyannote模型实现说话人分离,并提供了完整的代码实现、环境搭建指南以及核心的对齐与合并逻辑,帮助开发者高效处理会议录音、访谈等多说话人音频,实现自动化转录。

threejs5artist的博客 640

android拍照获取图片路径,Android系统拍照之后回显并且获取文件路径

/*调用拍照返回*/case PHOTO_REQUEST_GALLERY:if (data != null) {Uri uri = data.getData();String photopath = null;Cursor cursor = LocationApplication.getContext().getContentResolver().query(uri, null, null, nu...

weixin_30070647的博客 1007

储能变流器(Power Control System——PCS)设计原理

储能变流器(Power Control System——PCS)可控制蓄电池的充电和放电过程,进行交直流的变换,在无电网情况下可以直接为交流负荷供电。PCS 由 DC/AC 双向变流器、控制单元等构成。PCS 控制器通过通讯接收后台控制指令,根据功率指令的符号及大小控制变流器对电池进行充电或放电,实现对电网有功功率及无功功率的调节。 PCS 控制器通过 CAN 接口与 BMS 通讯,获取电池组状态信息,可实现对电池的保护性充放电,确保电池运行安全。   储能变流器(PCS)可控制蓄电池的充电和放电过程,进

Zhouengineer的博客 5万+

java批处理读取照片_〔批处理〕从数码相片得到照相时间

@ECHO OFFSETLOCAL EnableDelayedExpansionDEL /F /Q picture.txt 2>NUL:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 原理::::: 一般情况下,有EXIF信息的照片,会有三处时间(当然还有特例),第一处格式...

weixin_42365251的博客 231

支付系统保证可靠性的秘诀 ----- 订单的补偿和补单

文章目录WHAT? 前言WHY? 为什么要用多级缓存?HOW 怎么做?方案 版本1:数据库存储专线配置通过优先级进行动态上下线方案 版本1 劣势:方案 版本2 :本地缓存替代数据库方案 版本2 劣势:方案 版本3:分布式缓存做自动补偿方案 版本3 总结:Where 分布式多级缓存还能用在哪些地方?总结 WHAT? 前言 刚入职场的时候觉得支付宝等第三方支付系统好强大,要保证这么多的交易不能错,也不能重复还要保证正确的扣钱,直到后面接触订单系统以及第三方支付公司的核心交易系统后才真正窥探到了支付系统的核心

boboaisisi的专栏 3536

C#客户端对接工厂MES的方法

本文介绍了使用C#实现WebApi客户端与工厂MES系统交互的方法。主要包括四个步骤:1)配置工控机IP地址;2)获取服务器URL;3)创建HttpHelper帮助类实现单例模式HttpClient,提供异步POST请求方法;4)通过实例化帮助类实现设备状态数据的JSON格式发送与接收。该方案采用异步通信方式,支持超时处理,能够满足大多数MES系统交互需求,帮助工程师快速完成设备与MES系统的数据对接。文中给出了核心代码片段和完整的数据交互流程示例。

weixin_39832501的博客 273

使用flash摄像头拍照的简单实践

打开Flash CS3,新建一个Flash文件(Script 2.0)。命名为pagea.fla 第一步:      在库中建立一个视频元件,类型选择:视频(受 ActionScript 控制)。      按F11打开库面板,右键空白地方出现一个弹出菜单,选择“新建视频”,随便起个名字。 第二步:      将视频元件拖到场景中,并调整尺寸到想要的大小。并起名为“camera”。同时在该图层...

菜菜 430

Serdes之什么是(CDR)?

光收发器和电收发器使用的是我们所说的串行数据通信。在这种通信方式中,数据位是按顺序一个接一个地传输的。光收发器和电收发器使用的是我们所说的串行数据通信。在这种通信方式中,数据位是按顺序一个接一个地传输的。目前市场上大多数收发器都没有专用的时钟输入,因此时钟恢复和数据重新定时等功能是在收发器外部(即在主板上)进行的。接收端则需要恢复时钟以采样串行线上的数据。为了实现这一点,接收端需要一个与输入数据频率大致相同的时钟。通过使参考时钟与输入数据信号的跳变相位对齐,可以生成一个恢复的时钟。这被称为时钟恢复。

叫好与叫座虽然不是对立面,但想在同一个作品中达到双重效果很难。 2404

Java:实现修改图片文件名 (附带源码)

Java:实现修改图片文件名 (附带源码)

欢迎来到我的博客!这里是一个专注于计算机技术的分享平台,涵盖编程开发、算法研究、系统架构、软件工程等多个领域。无论你是初学者还是资深开发者,都能在这里找到有价值的内容。 848

OpenCv —— 检测车牌号(附完整源码)

OpenCv —— 检测车牌号

5603

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

camera.swf java,使用flash摄像头拍照的简单实践 | 学步园

打开Flash CS3,新建一个Flash文件(Script 2.0)。命名为pagea.fla第一步: 在库中建立一个视频元件,类型选择:视频(受 ActionScript 控制)。 按F11打开库面板,右键空白地方出现一个弹出菜单,选择“新建视频”,随便起个名字。第二步: 将视频元件拖到场景中,并调整尺寸到想要的大小。并起名为“camera”。同时在该图层放置两个...

weixin_35382961的博客 262

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Android 调用摄像头功能【拍照与视频】

版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/ma_hoking/article/details/28292973 ...

weixin_30377461的博客 968

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

JAVA实现批量修改文件名称

假设你某天跟朋友出去玩,使用某数码相机拍摄了一些照片 但是当你回来的时候你发现所有的照片都是如下命名的 P1020335.JPG P1020336.JPG P1020337.JPG P1020338.JPG P1020339.JPG … 这些文件名实际上是自动生成的,对你来说不方便看。 你现在希望将这些照片都改成“2016-4-15-i” i表示第几张照片如 2016-4-1...

码匀的博客 6806

Java爬虫实战代码

业务背景 大家在平时的生活或工作种多少都会遇到类似下面的情况吧 非技术人员: 我身边有同学在一家装修设计公司上班,她每天的工作就是去其他各大装修平台,去“借鉴”别人家设计师的创意,找到合适的图片,就会一张张点击图片另存到自己电脑中。 其实这些工作都是重复性且毫无技术含量,完全可以用工具自动化实现。 技术人员: 比如我喜欢看一些技术帖子(微信公总号,技术博客等),有时候会觉得文章中的一些...

xiongyouqiang的博客 1万+
上一篇: 〔批处理〕搜索可疑文件内部的可疑关键字
下一篇: 〔Ajax〕随感
NeedJava
博客等级 码龄20年 15粉丝 36原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址