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

问题描述 投票:1回答:6

我有一个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.感谢提前。

batch-file cmd image-file
6个回答
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

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来检查这是否正常工作(如果添加c:\ python27,请输入您的PATH环境变量,只需键入“Python”)。这将打开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
投票

这是一个tooltipInfo.bat(可以用作.bat的jscript \ 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


1
投票

下面的代码基于tooltipInfo.batnpocmaka,除了我使用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);

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

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

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


0
投票

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

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

@ECHO result: %dimensions%
© www.soinside.com 2019 - 2024. All rights reserved.