ratio2.pl to HTML.

index -|- end

Generated: Sat Oct 24 16:35:27 2020 from ratio2.pl 2017/06/11 2.7 KB. text copy

#!/usr/bin/perl
#< ratio.pl - 20130618 - given width and height show aspect ration
# 2017-06-11 - Add ratio like 1024 768 = 4:3
use strict;
use warnings;

sub prt($) { print shift; }

sub isdig($) {
    my $txt = shift;
    return 1 if ($txt =~ /^\d+$/);
    return 0;
}

sub show_help() {
    prt("Give image width x height, to show aspect ratio...\n");
    prt("If a target width also given with show the target sizes...\n");
    prt("Can be width x height [target], or wxh [target]\n");
}

my @av = @ARGV;
my $width = 1;
my $height = 1;
my $ratio = 1;
my $targ_wid = 0;
my ($w,$h);
my $rat = '';


if (@av) {
    my ($itm,@arr,$cnt,$acnt);
    $cnt = 0;
    foreach $itm (@av) {
        if ($itm =~ /^-/) {
            prt("Unknown parameter [$itm]. Showing help...\n");
            show_help();
            exit(0);
        }
        if ($itm eq 'x') {
            # nothing to do
        } elsif ($itm =~ /x/) {
            @arr = split("x",$itm);
            $acnt = scalar @arr;
            if ($acnt == 2) {
                $width = $arr[0];
                $height = $arr[1];
                $ratio = $width / $height;
                $cnt = 2;
            } else {
                prt("Item [$itm] did NOT split on 'x' into two! Got $acnt\n");
                exit(1);
            }
        } else {
            if (isdig($itm)) {
                if ($cnt == 0) {
                    $width = $itm;
                } elsif ($cnt == 1) {
                    $height = $itm;
                } else {
                    $targ_wid = $itm;
                }
                $cnt++;
            } else {
                prt("Value given '$itm' is not an integer...\n");
                exit(1);
            }
        }
    }
    $w = $width;
    $h = $height;
    if ((int($w) == $w) && (int($h) == $h)) {
        $cnt = 0;
        while ((($w % 2) == 0) && (($h % 2) == 0)) {
            $w /= 2;
            $h /= 2;
            $cnt++;
        }
        if ($cnt) {
            $rat = "$w:$h";
        }
    }
    $ratio = $width / $height;
    if ($targ_wid > 0) {
        my ($xwid,$yhgt);
        if ($ratio > 1) {   # width > height
            $xwid = $targ_wid; # set target width
            $yhgt = int($targ_wid / $ratio); # and calculate NEW height
       } else {
         $xwid = int($targ_wid * $ratio); # calculate width
         $yhgt = $targ_wid; # and set target width as height
        }
        prt("Given w=$width, h=$height, ratio=$ratio target=$xwid".'x'."$yhgt $rat\n");
    } else {
        prt("Given width=$width, and height=$height, the ratio is $ratio $rat\n");
    }
} else {
    prt("Give image width x height, to show aspect ratio...\n");
}

# eof

index -|- top

checked by tidy  Valid HTML 4.01 Transitional