Get image file dimensions in .bat file

こ雲淡風輕ζ 提交于 2020-01-12 04:01:26

问题


I have a bat file that lists the paths of all images in a folder the code is

@echo off
break > infofile.txt
for /f "delims=" %%F in ('dir /b /s *.bmp') do (
   echo %%F 1 1 1 100 100 >>infofile.txt 
)


The text file looks like this

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  

What I want to do is replace the 100 100 at the end by the dimentions of each image width and height.. Thanks in advance.


回答1:


you can use 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

output example:

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:


Here's a tooltipInfo.bat (jscript\bat hybrid that can be used as a .bat) that takes the tooptip information for a file and does not require any external software:

@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();

Output if used against a picture:

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

so you can:

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

EDIT: Another way with WIA.ImageFile object - imgInfo.bat




回答3:


I'm not sure whether you will be able to get at file properties like that in a batch script. I would recommend using something like Python. Here is a link to another thread which suggests using the PIL.imaging library for this.

If you are interested in perusing this route but do not know any Python let me know and I can put a quick script together for this.

Instructions to install Python

As discussed you will need to install Python for this to run. I have also found out that PIL is a third party library, so you will also need to download and install this (make sure you pick the same version as your python installation e.g. if you have installed Python 2.7 on 64 bit, you would need "Pillow-2.1.0.win-amd64-py2.7.exe" from here).

Once you have done the install you can check that this is working by opening the command prompt (cmd) and entering c:\python27\python.exe (if you add c:\python27 top your PATH environment variable you will just need to type "Python"). This will open the python command prompt. Type print "test" and you should see thr output printed then exit().

Once Python is installed you can create a script. Here is some code that will do what you have requested (list all files of a given extension that are found from a base path with 1 1 1 width height to a file).

Open a text editor e.g. notepad paste in the code below and save as "image_attr.py" or whatever name you decide to use:

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()

Save this and remember the path to the file, I will use c:\python27\image_attr.py for this example. You can then call this from cmd or from a batch script passing in an arguement for the base path e.g.:

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

Please note that any arguements with spaces in them should be enclosed with double quotes.

Please let me know if you have any questions.

EDIT

For Python 3 the amendments should be minimal in theory. In this case I am writing the output the the screen rather than a file, but redirecting to a file from 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()

Call with:

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



回答4:


The code below is based on tooltipInfo.bat by npocmaka except that I used ExtendedProperty() instead of 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);



回答5:


This can be done with PowerShell with the Wia.ImageFile

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
}

The benifit is most windows computers have powershell instaled

It seams slower than CMD/batch scripts

That said CMD/batch scripts can't do this as far as I know.




回答6:


Install imagemagick, then use the following inside a batch file:

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

@ECHO result: %dimensions%


来源:https://stackoverflow.com/questions/18855048/get-image-file-dimensions-in-bat-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!