在.bat文件中获取图像文件尺寸

时间:2013-09-17 16:25:40

标签: batch-file cmd image-file

我有一个bat文件,列出代码

的文件夹中所有图像的路径
@echo off
break > infofile.txt
for /f "delims=" %%F in ('dir /b /s *.bmp') do (
   echo %%F 1 1 1 100 100 >>infofile.txt 
)


文本文件如下所示

C:\Users\Charles\Dropbox\trainer\temp\positive\rawdata\diags(1).bmp 1 1 1 100 100  
C:\Users\Charles\Dropbox\trainer\temp\positive\rawdata\diags(348).bmp 1 1 1 100 100  
C:\Users\Charles\Dropbox\trainer\temp\positive\rawdata\diags(353).bmp 1 1 1 100 100  

我想要做的是将每个图像宽度和高度的尺寸替换为100 100.提前感谢。

6 个答案:

答案 0 :(得分:7)

您可以使用MediaInfo

@ECHO OFF &SETLOCAL
(for /r %%a in (*.jpg *.bmp *.png) do (
    set "width="
    set "height="
    for /f "tokens=1*delims=:" %%b in ('"MEDIAINFO --INFORM=Image;%%Width%%:%%Height%% "%%~a""') do (
        echo(%%~a 1 1 1 %%~b %%~c
    )
))>infofile.txt
type infofile.txt

输出示例:

C:\Users\Private\Pictures\snap001.png 1 1 1 528 384
C:\Users\Private\Pictures\snap002.png 1 1 1 1920 1080
C:\Users\Private\Pictures\snap003.png 1 1 1 617 316
C:\Users\Private\Pictures\snap004.png 1 1 1 1920 1080
C:\Users\Private\Pictures\snap005.png 1 1 1 514 346
C:\Users\Private\Pictures\snap006.png 1 1 1 1920 1080
C:\Users\Private\Pictures\snap007.png 1 1 1 395 429
C:\Users\Private\Pictures\snap008.png 1 1 1 768 566
C:\Users\Private\Pictures\snap009.png 1 1 1 1536 1080
C:\Users\Private\Pictures\snap010.png 1 1 1 1600 480

答案 1 :(得分:2)

我不确定您是否能够在批处理脚本中获取类似的文件属性。我建议使用像Python这样的东西。 Here是另一个线程的链接,建议使用PIL.imaging库。

如果您有兴趣仔细阅读这条路线,但不知道任何Python让我知道,我可以为此快速编写脚本。

安装Python的说明

如上所述,您需要install Python才能运行此功能。我还发现PIL是第三方库,因此您还需要下载并安装它(确保选择与python安装相同的版本,例如,如果您在64位上安装了Python 2.7,则需要“ Pillow-2.1.0.win-amd64-py2.7.exe“来自here)。

完成安装后,您可以通过打开命令提示符(cmd)并输入c:\python27\python.exe来检查这是否正常工作(如果您在PATH环境变量中添加c:\ python27,则只需输入“蟒蛇”)。这将打开python命令提示符。输入print "test",您应该看到打印出来的输出exit()

安装Python后,您可以创建脚本。下面是一些代码可以执行您所请求的内容(列出从基本路径找到的给定扩展名的所有文件,文件的宽度为1 1 1)。

打开文本编辑器,例如记事本粘贴在下面的代码中并保存为“image_attr.py”或您决定使用的任何名称:

from PIL import Image
import os, sys

def main():

    # if a cmd line arg has been passed in use as base path...
    if len(sys.argv) > 1:
        base_path = sys.argv[1]
    # else use current working dir...
    else:
        base_path = os.getcwd()

    # image file extensions to be included, add or remove as required...
    ext_list = ['.bmp', '.jpg']

    # open output file...
    outfile = os.path.join(base_path,'infofile.txt')
    file_obj = open(outfile, 'wb')

    # walk directory structure...
    for root, dirs, files in os.walk(base_path):
        for f in files:

            # check of file extension is in list specified above...
            if os.path.splitext(f)[1].lower() in ext_list:
                f_path = os.path.join(root, f)
                width, height = Image.open(f_path).size
                output = f_path + ' 1 1 1 ' + str(width) + ' ' + str(height) +'\r\n'
                file_obj.write(output)

    file_obj.close()

if __name__ == '__main__':
    main()

保存并记住文件的路径,我将在此示例中使用c:\python27\image_attr.py。然后,您可以从cmd或批处理脚本中调用此方法,传入基本路径的争论,例如:

python c:\python27\image_attr.py E:\Users\Prosserc\Pictures

请注意,任何带有空格的争论都应附上双引号。

如果您有任何疑问,请与我们联系。

修改

对于Python 3,修正案在理论上应该是最小的。在这种情况下,我将输出写入屏幕而不是文件,但是从cmd重定向到文件:

from PIL import Image
import os, sys

def main():

    # if a cmd line arg has been passed in use as base path...
    if len(sys.argv) > 1:
        base_path = sys.argv[1]
    # else use current working dir...
    else:
        base_path = os.getcwd()

    # image file extensions to be included, add or remove as required...
    ext_list = ['.bmp', '.jpg']

    # walk directory structure
    for root, dirs, files in os.walk(base_path):
        for f in files:

            # check of file extension is in list specified above...
            if os.path.splitext(f)[1].lower() in ext_list:
                f_path = os.path.join(root, f)
                width, height = Image.open(f_path).size
                output = f_path + ' 1 1 1 ' + str(width) + ' ' + str(height) +'\r\n'
                print(output) 

if __name__ == '__main__':
    main()

致电:

python c:\python27\image_attr.py E:\Users\Prosserc\Pictures > infofile.txt

答案 2 :(得分:2)

这是一个tooltipInfo.bat(jscript \ bat混合,可用作.bat),它获取文件的tooptip信息,不需要任何外部软件:

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    rem :: the first argument is the script name as it will be used for proper help message
    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

////// 
FSOObj = new ActiveXObject("Scripting.FileSystemObject");
var ARGS = WScript.Arguments;
if (ARGS.Length < 1 ) {
 WScript.Echo("No file passed");
 WScript.Quit(1);
}
var filename=ARGS.Item(0);
var objShell=new ActiveXObject("Shell.Application");
/////


//fso
ExistsItem = function (path) {
    return FSOObj.FolderExists(path)||FSOObj.FileExists(path);
}

getFullPath = function (path) {
    return FSOObj.GetAbsolutePathName(path);
}
//

//paths
getParent = function(path){
    var splitted=path.split("\\");
    var result="";
    for (var s=0;s<splitted.length-1;s++){
        if (s==0) {
            result=splitted[s];
        } else {
            result=result+"\\"+splitted[s];
        }
    }
    return result;
}


getName = function(path){
    var splitted=path.split("\\");
    return splitted[splitted.length-1];
}
//

function main(){
    if (!ExistsItem(filename)) {
        WScript.Echo(filename + " does not exist");
        WScript.Quit(2);
    }
    var fullFilename=getFullPath(filename);
    var namespace=getParent(fullFilename);
    var name=getName(fullFilename);
    var objFolder=objShell.NameSpace(namespace);
    var objItem=objFolder.ParseName(name);
    //https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx
    WScript.Echo(fullFilename + " : ");
    WScript.Echo(objFolder.GetDetailsOf(objItem,-1));

}

main();

如果对照片使用输出:

C:\TEST.PNG :
Item type: PNG image
Dimensions: ?871 x 836?
Size: 63.8 KB

所以你可以:

for /f "delims=? tokens=2" %%a in ('toolTipInfo.bat C:\TEST.PNG ^|find "Dimensions:"')  do echo %%a

修改 使用 WIA.ImageFile 对象的另一种方法 - imgInfo.bat

答案 3 :(得分:1)

以下代码基于tooltipInfo.bat npocmaka,但我使用ExtendedProperty()代替GetDetailsOf()

@if (@X==@Y) @then
:: Batch
   @echo off & setLocal enableExtensions disableDelayedExpansion
(call;) %= sets errorLevel to 0 =%

(
    for /f "tokens=1,2 delims=x " %%X in ('
        cscript //E:JScript //nologo "%~dpf0" "%~dpf1" %2
    ') do (set "width=%%X" & set "height=%%Y") %= for /f =%
) || goto end %= cond exec =%
echo("%~nx1": width=%width% height=%height%

:end - exit program with appropriate errorLevel
endLocal & goto :EOF

@end // JScript

// objects
var FSOObj = WScript.CreateObject("Scripting.FileSystemObject"),
    objShell = WScript.CreateObject("Shell.Application");

var ARGS = WScript.Arguments;
if (ARGS.length != 1) {
WScript.StdErr.WriteLine("too many arguments");
    WScript.Quit(1);
} else if (ARGS.Item(0) == "") {
    WScript.StdErr.WriteLine("filename expected");
    WScript.Quit(1);
} // if

ExistsItem = function (path) {
    return FSOObj.FolderExists(path) || FSOObj.FileExists(path);
} // ExistsItem

getFullPath = function (path) {
    return FSOObj.GetAbsolutePathName(path);
} // getFullPath

getParent = function(path) {
    var splitted = path.split("\\"), result = "";

    for (var s=0; s<splitted.length-1; s++) {
        if (s == 0) {
            result = splitted[s];
        } else {
            result = result + "\\" + splitted[s];
        } // if
    } // for

    return result;
} // getParent

getName = function(path) {
    var splitted = path.split("\\");
    return splitted[splitted.length-1];
} // getName

var filename = ARGS.Item(0),
    shortFilename = filename.replace(/^.+\\/, '');
if (!ExistsItem(filename)) {
   WScript.StdErr.WriteLine('"' + shortFilename + '" does not exist');
    WScript.Quit(1);
} // if

var fullFilename=getFullPath(filename), namespace=getParent(fullFilename),
    name=getName(fullFilename), objFolder=objShell.NameSpace(namespace),
    objItem;
if (objFolder != null) {
    objItem=objFolder.ParseName(name);
    if (objItem.ExtendedProperty("Dimensions") != null) {
        WScript.Echo(objItem.ExtendedProperty("Dimensions").slice(1, -1));
    } else {
        WScript.StdErr.WriteLine('"' + shortFilename +
            '" is not an image file');
        WScript.Quit(1);
    } // if 2
} // if 1

WScript.Quit(0);

答案 4 :(得分:0)

使用Wia.ImageFile

的PowerShell可以完成此操作
break>infofile.txt
$image = New-Object -ComObject Wia.ImageFile
dir . -recurse -include *.jpg, *.gif, *.png, *.bmp | foreach{
  $fname =$_.FullName
  $image.LoadFile($fname)
  echo ($fname -replace "\\","/" 1 1 1 $image.Width $image.Height)>>infofile.txt
}

好处是大多数Windows计算机都有PowerShell instaled

它接缝慢于CMD /批处理脚本

据我所知,CMD /批处理脚本不能这样做。

答案 5 :(得分:0)

安装imagemagick,然后在批处理文件中使用以下命令:

FOR /F "tokens=* USEBACKQ" %%F IN (`magick identify -format "%%wx%%h" %1`) DO (SET dimensions=%%F)

@ECHO result: %dimensions%