Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Batch file 获取.bat文件中的图像文件尺寸_Batch File_Cmd_Image File - Fatal编程技术网

Batch file 获取.bat文件中的图像文件尺寸

Batch file 获取.bat文件中的图像文件尺寸,batch-file,cmd,image-file,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

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

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

如果您对阅读这条路线感兴趣,但不了解任何Python,请告诉我,我可以为此编写一个快速脚本

安装Python的说明

正如前面所讨论的,您将需要为运行此功能而安装。我还发现,PIL是一个第三方库,因此您还需要下载并安装它(请确保选择与python安装相同的版本,例如,如果您在64位上安装了python 2.7,则需要来自的“Pizz-2.1.0.win-amd64-py2.7.exe”)

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

一旦安装了Python,就可以创建一个脚本。下面是一些代码,它们将执行您所请求的操作(列出给定扩展名的所有文件,这些文件是从一个文件的宽度和高度为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\u 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
您可以使用:

输出示例:

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
下面是一个(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();
因此,您可以:

for /f "delims=? tokens=2" %%a in ('toolTipInfo.bat C:\TEST.PNG ^|find "Dimensions:"')  do echo %%a
编辑:
使用WIA.ImageFile对象的另一种方法-

可以使用带

好处是大多数windows计算机都安装了powershell

它比CMD/批处理脚本慢


就我所知,CMD/batch脚本无法执行此操作。

下面的代码基于by,但我使用了而不是

@如果(@X==@Y)@那么
::批量
@echo off&设置本地启用扩展禁用延迟扩展
(call;)%=将errorLevel设置为0=%
(
对于/f“令牌=1,2 delims=x”%%x in('
cscript//E:JScript//nologo“%~dpf0”“%~dpf1”%2
“)do(设置“宽度=%%X”和设置“高度=%%Y”)%=for/f=%
)| |转到结束%=继续执行=%
回声(“%nx1”):宽度=%宽度%height=%height%
:结束-退出具有适当错误级别的程序
endLocal和goto:EOF
@结束//JScript
//物体
var FSOObj=WScript.CreateObject(“Scripting.FileSystemObject”),
objShell=WScript.CreateObject(“Shell.Application”);
var ARGS=WScript.Arguments;
如果(ARGS.length!=1){
WScript.StdErr.WriteLine(“参数太多”);
WScript.Quit(1);
}else if(参数项(0)==“”){
WScript.StdErr.WriteLine(“需要文件名”);
WScript.Quit(1);
}//如果
ExistsItem=函数(路径){
返回FSOObj.FolderExists(路径)| | FSOObj.FileExists(路径);
}//现有站点
getFullPath=函数(路径){
返回FSOObj.GetAbsolutePathName(路径);
}//获取完整路径
getParent=函数(路径){
var splitted=path.split(“\\”),result=“”;
对于(var s=0;s安装,请在批处理文件中使用以下命令:

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

@ECHO result: %dimensions%

是的,如果你不介意的话,请告诉我我以前从未使用过python。我只需要一个脚本,其中列出了文件路径的高度和宽度为1…谢谢这不是对所问问题的回答。它应该是对原始问题的评论。@KenWhite我知道你是从哪里来的,但问题是关于如何列出图像和文件的详细信息这就是我的答案试图解决的问题,只是使用了与问题中提到的不同的脚本语言。@CharlesOsei我应该提到,这将涉及到安装Python,因为默认情况下它不随Windows一起提供。您可以从这里学习:如果您有64位操作系统,请使用“Python 2.7.5 Windows X86-64安装程序”,如果您使用的是32位或不知道,请使用“Python 2.7.5 Windows Installer”。我将编写一个脚本,您可以很快从批处理文件调用该脚本,并将其添加到上面的答案中。@ChrisProsser:这个问题专门询问标记中的“批处理文件”和文本中的“.bat”文件。它没有说“请推荐一些方法”考虑一下如何修理你的Windows 7计算机,并得到一个回答:“使用MAC代替”。-对于某些人来说,Mac电脑可能是一种替代品,但对于电脑死机、期限紧迫的人来说,它现在并不是他们问题的解决方案。工具提示并不总是包含有关图像维度的信息。将
31
而不是
-1
作为
GetDetailsOf
的第二个参数传递给你维度。
31
是一个神奇的数字,可以在下面的注释“使用GetDetailsOf方法和有用的示例完整枚举详细信息”中找到:AndrewThatTechGuy@AlessandroJacopson-有趣。我将设置幻数作为第二个参数,以使我的脚本更灵活。这是一个出色的解决方案,以备您使用
for /f "delims=? tokens=2" %%a in ('toolTipInfo.bat C:\TEST.PNG ^|find "Dimensions:"')  do echo %%a
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
}
@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);
FOR /F "tokens=* USEBACKQ" %%F IN (`magick identify -format "%%wx%%h" %1`) DO (SET dimensions=%%F)

@ECHO result: %dimensions%