Page 1 of 1

Foreach; return to next file after a failure on one file

Posted: 24 Oct 2012 20:49
by klownboy
Hi, I've been working on a script which crops photos to specific aspect ratios which you can then use to apply as a wallpaper on monitors with different aspect ratios. I found myself going into Irfanview or similar graphic programs to crop photos and wallpaper to these different aspect ratios on my three computers. And, who hasn't downloaded other pictures or wallpapers from the internet that for example, maybe in 1920x1200 format and you want to crop it quickly to 1900x1080 (wide screen). The script crops, doesn't resize so you don't loose quality or the original photo for that matter. The script worked and still does, just fine until I decided to make it work for more than one selected photo or picture. I used a "foreach" command to make it run on more than one file. With the foreach command, the cycle or loop works as expected unless an error occurs (I've built in a little error control) like for example, if the selected file isn't a picture or you're attempting to crop to a 16x9 aspect ratio and the photo is already in that aspect ratio. I'm having a difficult time with error control and getting the script to return to the next selected file in foreach command when it with the encounters an error with a file (e.g., the file is not a picture or image or is already in the aspect ratio I'm trying to achieve). Any help would be very much appreciated.

Code: Select all

"CROP PHOTO to ASPECT RATIO" //|D:\Graphics\Icons\k321-icon-219.ico"        // see sub "_ExecuteIV" to modify Irfanview path to suit your installation
   load self(file);
"      16x9 (e.g., 1920x1080)|D:\Graphics\Icons\k321-icon-218.ico";        // maintains the highest possible file size and only crops to achieve a 16x9 aspect ratio;
 
  global $x_crop, $y_crop, $xy, $rotate, $orig_width, $orig_height, $orig_ratio, $width, $height;
  global $file;

  foreach($token, <get selecteditemspathnames |>) {
   $file = $token;
   $xy = "16x9";
   sub "_FileChk";
                                                           // when going "to" 16x9 we will always be cropping in the y axis at least for standard photography
    $height = ($orig_width * 9) / 16;                      // echo "Test 1: New height is ". $height ."";
    $y_total_crop = $orig_height - $height;
    $y_crop = round ($y_total_crop / 2);                   // msg "Crop amount is ". $y_crop ."";
 
    $y_crop = input("Crop offset [y] vertically down from upper left corner 0,0.","Enter number from 1 to ". $y_total_crop .", e.g., ". $y_crop ." centers crop." , $y_crop, "s", ,300,250);
    $width = $orig_width; $x_crop = "0"; sub "_ExecuteIV";
    }
    
"      8x5 (e.g., 1920x1200)|D:\Graphics\Icons\k321-icon-219.ico";          // maintains the highest possible file size and only crops to 8x5 aspect ratio
  global $x_crop, $y_crop, $xy, $rotate, $orig_width, $orig_height, $orig_ratio, $width, $height;
  global $file;
  foreach($token, <get selecteditemspathnames |>) {
    $file = $token;
    $xy = "8x5";
    sub "_FileChk";

    if ($orig_ratio > 1.6) {                // If ratio is > 1.6 which is an 8x5, we must crop on the x axis (e.g., Panasonic camera 4320 x 2430 (16x9) to a 8x5)
       $width = round (($orig_height * 8) / 5);
       $x_total_crop = $orig_width - $width;
       $x_crop = round ($x_total_crop / 2);                  // msg "Crop amount is ". $x_crop ."";

       $x_crop = input("Crop offset [x] horizontally across from upper left corner 0,0.","Enter number from 1 to ". $x_total_crop .", e.g., ". $x_crop ." centers crop."  , $x_crop, "s", ,300,250);
       $height = $orig_height; $y_crop = "0"; sub "_ExecuteIV";                   //$height is actually the same in this case since we are cropping [x]
       }
     else {
       $height = ($orig_width * 5) / 8;                       //echo "Test 1: New height is ". $height ."";
       $y_total_crop = $orig_height - $height;
       $y_crop = round ($y_total_crop / 2);                   //msg "Crop amount is ". $y_crop ."";
   
       $y_crop = input("Crop offset [y] vertically down from upper left corner 0,0.","Enter number from 1 to ". $y_total_crop .", e.g., ". $y_crop ." centers crop." , $y_crop, "s", ,300,250);
       $width = $orig_width; $x_crop = "0"; sub "_ExecuteIV";
       }
     }
"      4x3 (e.g., 1600x1200)|:viewthumbs";                 // maintains the highest possible file size and only crops to 4x3 aspect ratio

  global $x_crop, $y_crop, $xy, $orig_width, $orig_height, $orig_ratio, $width, $height;
  global $file;
  foreach($token, <get selecteditemspathnames |>) {
    $file = $token;
    $xy = "4x3";
    sub "_FileChk";

    if ($orig_ratio > 1.33) {                                // If ratio is > 1.33 which is an 4x3, we must crop on the x axis (e.g., Panasonic camera 4320 x 2430 (16x9) to a 8x5)
       $width = round (($orig_height * 4) / 3);
       $x_total_crop = $orig_width - $width;
       $x_crop = round ($x_total_crop / 2);                  //msg "Crop amount is ". $x_crop ."";

       $x_crop = input("Crop offset [x] horizontally across from upper left corner 0,0.","Enter number from 1 to ". $x_total_crop .", e.g., ". $x_crop ." centers crop."  , $x_crop, "s", ,300,250);
       $height = $orig_height; $y_crop = "0"; sub "_ExecuteIV";                   //$height is actually the same in this case since we are cropping [x]
       }
    else {
       $height = ($orig_width * 3) / 4;                      //echo "Test 1: New height is ". $height ."";
       $y_total_crop = $orig_height - $height;
       $y_crop = round ($y_total_crop / 2);                  //msg "Crop amount is ". $y_crop ."";
   
       $y_crop = input("Crop offset [y] vertically down from upper left corner 0,0.","Enter number from 1 to ". $y_total_crop .", e.g., ". $y_crop ." centers crop." , $y_crop, "s", ,300,250);
       $width = $orig_width; $x_crop = "0"; sub "_ExecuteIV";
       }
    }

"_FileChk";
  global $file, $token, $p, $xy, $rotate, $orig_width, $orig_height, $orig_ratio;

   End GetInfo("CountSelected") < 1, "No file(s) have been selected.";
   $p = property("#11", $file);                       // determine if the file is a picture
   if ($p != "Picture") {                                    // checks properties to make sure it's an image/picture
       msg "This is not a picture image so you can't crop it.";
       end 1==1,, 1;
       }
   $d = property(dimensions, $file);
   $rotate = property("#245", $file);
   $orig_width = property("ImageX", $file);              // another method,   $orig_width = gettoken($d, 1, " x ");
   $orig_height = property("ImageY", $file);
   $orig_ratio = round ($orig_width / $orig_height, 2);      // msg "Original ratio is ". $orig_ratio ."";

   if ($orig_width * $orig_height < 50000) {                 // you can decrease this # to crop smaller images
      msg "This image is a bit small to crop ". $d . " px!";
      end 1==1,, 1;
       }
   if ($rotate != "Rotate 270 degrees") {                    // If picture is rotated, it's in "portrait" and will have a ratio < 1 and will not be a concern for these checks
     if ($orig_ratio == 1.33 AND ($xy == 4x3)) {             // checks to see if the picture is already in 4x3 aspect ratio
      msg "This picture is already in a 4x3 aspect ratio, ". $d . " px!";
      end 1==1,, 1;
      }
     if ($orig_ratio == 1.6 AND ($xy == 8x5)) {              // checks to see if the picture is already in 8x5 aspect ratio
      msg "This picture is already in a 8x5 aspect ratio, ". $d . " px!";
      end 1==1,, 1;
      }
     if ($orig_ratio == 1.78 AND ($xy == 16x9)) {            // checks to see if the picture is already in 16x9 aspect ratio
      msg "This picture is already in a 16x9 aspect ratio, ". $d . " px!";
      end 1==1,, 0;
      }
   }
   else {
     $orig_width = property("ImageY", $file);           //  Reverses X and Y axis since these photos are rotated 270 degrees- need to reverse for std crop calculations
     $orig_height = property("ImageX", $file);
     } 
     
"_ExecuteIV";
  global $x_crop, $y_crop, $xy, $rotate, $width, $height, $file;
 
  $path=getpathcomponent($file, "path");
  $base=getpathcomponent($file, "base");
  $ext=getpathcomponent($file, "ext");
  $new_file = "$path\$base" . "_$xy.$ext";                   //     $new_file = gettoken ($file, 1,".")" . "_$xy.$ext";

  $g_IrfanPath="d:\graphics\irfanView\i_view32.exe";
  run """$g_IrfanPath"" $file /aspectratio /jpgq=100 /crop=($x_crop, $y_crop, $width, $height) /convert=$new_file", , 2,0;
  wait(500);
  
I originally intended to put this in the script section without the multiple file capability since it worked great without it, but I was hoping to get this working for a multiple file selection. I've tried different "end" options without any luck. Maybe it has to be totally restructured, but I was hoping not. I notice my nice bullets (alt 007) for each sub heading didn't show up when I pasted the code. :(
Thanks,
Ken

Re: Foreach; return to next file after a failure on one file

Posted: 24 Oct 2012 21:07
by Stefan
Hi Ken,

I think your whole lot of text can be reduced just to
I'm having a difficult time with error control and getting the script to return to the next selected file
in foreach command when it with the encounters an error with a file
(e.g., the file is not a picture or image or is already in the aspect ratio I'm trying to achieve).
Any help would be very much appreciated.
and i would appreciate it if you would do this analysis your self and come to the point (if i can say this in english like that)

The rest you may post as well if you want, but please make your initial question more clear for me.


To your question:

I think there is no ON ERROR RESUME NEXT or ON ERROR GoTo or TRY CATCH FAIL currently available.

You can only do a lot of checks at first place

and handle them with

if(x){..do..}else{..that..}

or

if(x){continue;}



For your problem i would try "readfile(filename,, [numbytes]); "
and check against magic strings to see if it is a picture.
Or invoke TrID - File Identifier for this work.
Or check just the file extension(s) if possible.
Do you need an how-to?



CU

Re: Foreach; return to next file after a failure on one file

Posted: 24 Oct 2012 21:51
by klownboy
Thanks Stefan, sorry for being wordy or not to the point.
I suppose I didn't have to explain the purpose/need for the script only the problem with it and the help I need.

The error control itself does work. I use property commands to check that it's a picture, check for image rotation, and check picture length and width, etc. It's the control after the error that's the problem. When the first file selected results in one of those failures, how do I properly proceed or jump over the subsequent steps and checks in the "sub" to the main script to start with the next selected file obtained in the foreach command.

Code: Select all

foreach($token, <get selecteditemspathnames |>) {
I hope that's clearer, but I'll work on a different structure possibly with more if/else structure. Note: The same script without the multiple file capablility via the foreach loop works fine even with the same error control.
Thanks again,
Ken

Re: Foreach; return to next file after a failure on one file

Posted: 24 Oct 2012 21:57
by highend
Are you looking for "break" instead of "end"?

Re: Foreach; return to next file after a failure on one file

Posted: 25 Oct 2012 03:20
by klownboy
Hi highend, I had tried using "break" and "break 2" even though the help file says it's for use in "while loops". I'm not so sure it will work or is suppose to work with all those "if" statements. I had no success when an error was encountered. I'll do some more playing with it. Is there any way to send it back upon an error using another "sub"? Or, maybe I'll try a while statement at the start of the sub. When I originally wrote this, I wrote it just to work with one file at a time using <curitem> instead of multiple files using "getpathcomponent" and "foreach" that's when it went foul.
Thanks for your help,
Ken
Edit: I just read that "break" and "continue" are supported with "foreach" so hopefully with a bit of restructuring I can get it working.

Re: Foreach; return to next file after a failure on one file

Posted: 25 Oct 2012 08:25
by highend
My "logic" is: The foreach / while loops should skip / not process items that don't meet the requirements / don't need to be processed.

so:

foreach($entry, $listOfFiles, "<delimiter>"){
if($condition_a == true) { rotate $entry }
elseif ($condition_b == true) { crop to xxx }
else { either do nothing or maybe msg some output something for those files / create a log for not processed entries / etc. }

I don't know if I really understand your problem but it seems you don't know what you want to do in the else clause...

but end() isn't the right option there because you'll not process any following items ;)

Please upload (anywhere) a picture that would fall into the else clause category so that we can see, what's the real problem.

Re: Foreach; return to next file after a failure on one file

Posted: 25 Oct 2012 11:18
by PeterH
I try to describe it with examples:

If I have a while-loop with entries to ignore, for example empty lines, I test for them and execute Continue:
If I have an item that should terminate processing of the loop it's break:

Code: Select all

   If ($item == "") {Continue;} // continues with next item of loop
   If ($item == "*end") {Break;} // terminates current loop
It is shown in Examples of Help. Though the example of Continue is a bit strange :roll:
(OK: *both* show Break and Continue without an If - and don't make much sense this way in a real program.)

By the way: in normal situations you "break" the current ("inner") While. But sure you sometimes might want to Break 2 (or more) nested loops at once. Same for Continue...

Re: Foreach; return to next file after a failure on one file

Posted: 25 Oct 2012 13:07
by Stefan
I have not inspected your whole script,
but as far as i see how you have written it,
i think i would just use a another global variable
to check in the main code if "_FileChk" returns "TRUE"

I other words, i guess
your "_FileChk" sub needs to return TRUE for "ok, lets do it" or FALSE for "stop and skip"

Code: Select all

"main"
   global $FileChkReturn;
   sub "_FileChk";

    if ($FileChkReturn=="TRUE"){
                  if ($orig_ratio > 1.33) {
                 -
                 -
                 -
                 }else{
                    sub "_ExecuteIV";
                 }
   }else{
              continue; //skip this file
   }


"_FileChk"
  global $FileChkReturn;
   $FileChkReturn = "FALSE";
   -
   -
   -
   if all went ok, $FileChkReturn = "TRUE"


"_ExecuteIV"
   -
   -
   -

otherwise, sorry if i don't get it :wink:

Re: Foreach; return to next file after a failure on one file

Posted: 25 Oct 2012 15:59
by klownboy
Thanks Stefan, highend, PeterH and SkyFrontier (via PM). It's working thanks to your suggestions. What got it working was a combination of the use of "condition (2)" (which properly returns the script from the sub) along with setting a global variable to false or "0" if any of the errors were encountered. If the variable is "0" then the remainder of the script in the main body is not performed, but it is if it's "1". Note to Stefan in part of your suggestion: I found that using a"continue" in the body did not work (i.e., the whole script ended and the next file was ignored).

Code: Select all

   }else{
              continue; //skip this file
but when I removed it, the script continues properly to the next file in the "foreach".
Again thanks so much for all the help,
Ken