3

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.

fmw42
  • 46,825
  • 10
  • 62
  • 80
Charles Osei
  • 175
  • 2
  • 3
  • 15

6 Answers6

9

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
Endoro
  • 37,015
  • 8
  • 50
  • 63
3

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

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 1
    tooltip does not always contain info about the dimension of image. Passing `31` instead of `-1` as second parameter of `GetDetailsOf`gives you the dimension. `31` is a magic number found in the comment "Full Enumeration of Details using the GetDetailsOf method with USEFUL example" at https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx by AndrewThatTechGuy – Alessandro Jacopson Apr 10 '15 at 13:07
  • @AlessandroJacopson - interesting.I'll set the magic number as a second parameter to make my script more flexible. – npocmaka Apr 10 '15 at 13:51
  • 1
    This is just a brilliant solution in case you use images built by some "solid" software.Thanks a lot! – lucifer63 Sep 05 '17 at 12:53
2

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
Community
  • 1
  • 1
ChrisProsser
  • 12,598
  • 6
  • 35
  • 44
  • yes please if you don`t mind ive never used python before.. i just need a script which lists file path with 1 1 1 height width ... thanks – Charles Osei Sep 17 '13 at 16:52
  • This is not an answer to the question asked. It should be a comment to the original question instead. – Ken White Sep 17 '13 at 16:58
  • @KenWhite I can see where you are coming from, but the question was about how to list details of the images and that is what my answer is attempting to address, just using a different scripting language to the one mentioned in the question. – ChrisProsser Sep 17 '13 at 17:24
  • @CharlesOsei I should mention that this would involve installing Python as it does not ship with Windows by default.You can pick it up from here: http://www.python.org/download/ if you have a 64-bit OS go for the "Python 2.7.5 Windows X86-64 Installer", if you are on 32-bit or don't know use the "Python 2.7.5 Windows Installer". I will work on a script that you could call from your batch file shortly and add to the answer above. – ChrisProsser Sep 17 '13 at 17:48
  • @ChrisProsser: The question specifically asks about "batch file" in the tags, and ".bat" file in the text. It doesn't say "please recommend some way to do this". Consider being asked how to repair your Windows 7 computer and getting an answer that says "Use a Mac instead" - while for some people a Mac might be an alternative, for the person with the dead PC and a pressing deadline it isn't the solution to their problem NOW. – Ken White Sep 17 '13 at 18:35
  • Thanks Chris, installing python now. – Charles Osei Sep 17 '13 at 18:36
  • @KenWhite I don't think that this is at all like suggesting some buy another computer because Python is free and easy to install. I am not suggesting for a moment that this is the only way to solve this problem, but it is a free and relatively easy way to solve this problem. If you have a better solution please feel free to post it. – ChrisProsser Sep 17 '13 at 18:41
  • I was trying to be polite and point this out instead of downvoting, but I'm not debating it with you. When Python becomes installed by default on Windows systems **and** becomes one of the choices of supported languages in batch files under `cmd.exe` and I don't see that happening real soon :-), this is not an answer to the question asked here. – Ken White Sep 17 '13 at 18:58
  • you can use [Imagemagick](http://www.imagemagick.org/script/index.php) in your batch. There might also be a solution with `wmic`. – Endoro Sep 17 '13 at 19:04
  • @KenWhite I think that we will just have to agree to disagree on this one. You can call a Python script from a batch file or from cmd.exe. You need to install Python first, but this is pretty easy and we are dealing with programmers here, it's not unusual to have to install a program or a library to solve a problem. – ChrisProsser Sep 17 '13 at 19:12
  • @CharlesOsei Sorry, I forgot to add the code to write to a file rather than the screen on the first version posted. I have just corrected this. Let me know if you have any problems. – ChrisProsser Sep 17 '13 at 19:22
  • Im happy to follow any other solutions if it solves my problems but i do understand what you mean Ken..... @ChrisProsser thanks, im getting a " SyntaxError: invalid syntax" line 28 print f_path, '1 1 1', width, height – Charles Osei Sep 17 '13 at 19:22
  • @CharlesOsei See my comment just above, this should be okay now. Did you install Python 3 by the way? If so this would explain the error with the print statement as this changed in Python 3. – ChrisProsser Sep 17 '13 at 19:26
  • yeah i did install python 3 by mistake haha, i should pay more attention ... i got a few more errors after updating the script... here`s a screenshot http://imgur.com/xbi2397 – Charles Osei Sep 17 '13 at 19:38
  • @CharlesOsei it looks like the PIL library has either not been installed, or not been installed correctly. Did you follow this part of the instructions? – ChrisProsser Sep 17 '13 at 19:45
  • @ChrisProsser: OK. I'm afraid I'll just have to downvote this as being wrong. :-) I agree you can *download and install Python and call it from a batch file*, but that was not the question that was asked here, and your answer is wrong for that question. (Future readers here searching for a way to do something in a batch file will not find anything relevant to that topic in your answer.) – Ken White Sep 17 '13 at 19:48
  • turns out i installed 2.7 PIL and had python 3.3, i`ve got the right version of PIL and now have slightly less errors...http://imgur.com/NEBEXB6 – Charles Osei Sep 17 '13 at 19:59
  • @CharlesOsei Which version of python are you running now? – ChrisProsser Sep 17 '13 at 20:07
  • @ChrisProsser python-3.3.2.amd64.msi and Pillow-2.1.0.win-amd64-py3.3 .. shall i downgrade to 2.7? – Charles Osei Sep 17 '13 at 20:11
  • It is up to you. I am happy to try to make amendments, but do not have version 3 installed myself, so it will be a bit of trail and error if we go that route as I will not be able to test the changes. There is a 2to3 library which does automatic conversion, so I will try this first. – ChrisProsser Sep 17 '13 at 20:15
  • @CharlesOsei 2to3 says no need to modify. So probably best if you do install 2.7 then try again. – ChrisProsser Sep 17 '13 at 20:29
  • @CharlesOsei I am posting a version that I think should work with Python 3 as an edit above incase you want to try this first. Note, that I have not been able to test this. – ChrisProsser Sep 17 '13 at 20:33
  • @CharlesOsei great news, please could you mark this as the accepted answer if you feel it has resolved the issue for you. – ChrisProsser Sep 17 '13 at 21:33
2

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);
Sponge Belly
  • 121
  • 1
  • 4
0

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.

haelmic
  • 541
  • 4
  • 18
0

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%
James John McGuire 'Jahmic'
  • 11,728
  • 11
  • 67
  • 78