0

Currently, My program is supposed to do the following

  1. Inside a for loop, check the file size of the first attachment.
  2. After checking file size, i will save the name of the file that it is reading.
  3. Do the algorithm to calculate the desired size and add KB at the back of it.
  4. Use ImageMagick to choose the desired path output, desired file size and input filename
for %S in Images\RAW_IMAGE\*.jpg) do set outsize=%~zS & set name=%~nxS  & set /a outsize=(outsize*80/100)/1024 & set outsize=%outsize%KB & cd Images\RAW_IMAGE & mogrify -path Images\COMPRESSED_IMAGE  -define jpeg:extent=%outsize% %name%

For some reason, i get this error after running it

: mogrify: unable to open image '%name%'

where it should be the file name as I've tested the code step by step for a singular file and it works.

I suspect that due to my lack of understanding of how code works in CMD, the outsize & name values are not updated.

I would appreciate it if anyone could give me some pointers on what I'm doing wrong.

tthh
  • 31
  • 6
  • Notwithstanding the fact that your code is incomplete, _(currently incorrect)_, you have a delayed expansion problem. I am not closing this immediately as a duplicate of [Variables are not behaving as expected](https://stackoverflow.com/q/30282784), because until your code is fixed, it is unlikely that you'll be able to translate the solution to what you have there. – Compo Nov 08 '19 at 11:36
  • I would suggest that if you are working with one image at a time in a loop and not a directory, use convert (IM6) or magick (IM7) rather than mogrify. It does not set output names. – fmw42 Nov 08 '19 at 17:58

1 Answers1

2

I do not have mogrify so I cannot test this batch file, so you would need to do the testing for us.

@echo off
setlocal enabledelayedexpansion
for %%i in (.\Images\RAW_IMAGE\*.jpg) do (
    set outsize=%%~zi
    set /a outsize=(outsize*80/100^)/1024
    set "name=%%~nxi"
    pushd .\Images\RAW_IMAGE
    mogrify -path Images\COMPRESSED_IMAGE  -define jpeg:extent=!outsize!KB !name!
    popd
)
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • Thanks so much, the code works, but can i just ask for clarification purposes, what is the purpose of the '^' symbol, as even after using delayedexpansion, my number seems funky but after adding in the '^' symbol, it manages to work perfectly on my original code. – tthh Nov 11 '19 at 03:08
  • The caret `^` is for escaping the closing patenthesis `)` else the code thinks that is where I am closing the loop of the `for` loop – Gerhard Nov 11 '19 at 04:44