I'm too bad in math! can't figure the correct function to resize   images

This is driving me crazy, just becasue I don't have the
logical brains it takes:
I want to dynamically (PHP) resize images, according to a max
width and max height parameters.
What's giving me a problem is that max width and max height
are not equal, AND the images should be
resized only if their original size is too big:
$max_width = 650;
$max_height = 500;
$size = getimagesize($image);
$img_width = $size[0];
$img_height = $size[1];
Now how do I write a function that will resize images of any
possible size, *only if they need to*,
to fit in the maximum size *rectangle*?...
I have tried for hours to get it right, and I am ending up
with a function so full of conditionals
and sub-sub-conditionals that I'm getting completely lost.
I hope you can help, I'm sure it should be very simple...
seb ( [email protected])
http://webtrans1.com | high-end web
design
Downloads: Slide Show, Directory Browser, Mailing List

here's the solution. This will correctly and proportionally
reduce image size according to ANY max
width and max height, no matter what the difference between
max width and max height:
if(($width <= $max_width) && ($height <=
$max_height)){
// The image is the right size already
$targetwidth = $width;
$targetheight = $height;
}else{
// if width > height
if($width >= $height){ // if height > width
$targetwidth = $max_width;
$targetheight = $targetwidth * ($height / $width);
// here we must check again if reduced height is not still
greater than max_height
if($targetheight > $max_height){
$targetheight = $max_height;
$targetwidth = $targetheight * ($width / $height);
}elseif($height > $width){ // if height > width
$targetheight = $max_height;
$targetwidth = $targetheight * ($width / $height);
// here we must check again if reduced width is not still
greater than max_width
if($targetwidth > $max_width){
$targetwidth = $max_width;
$targetheight = $targetwidth * ($height / $width);
(_seb_) wrote:
> Actually I did some tests, and it does not work!
>
> Here's the problem:
>
> $maxwidth = 600;
> $maxheight = 400; // max height is smaller than max
width!
>
> Then the method tests whether the image is taller or
wider, and resizes
> it to maxwidth or maxheight accordingly.
> So, if an image is 700px wide and 699px high, it will be
reduced
> according to $max_width, because the image is wider than
tall.
>
> *The resulting resized image will be taller than
$max_height*.
>
> That's the problem I have been running into.
>
> I cannot find a simple mathematic solution, without
getting lost in
> endless conditionals. I have found many examples of
resizing according
> to max width and max height parameters, but not one that
addresses this
> issue.
>
> (_seb_) wrote:
>> thanks Sonjey - that worked
>>
>> Sonjay wrote:
>>> This is the basic code that I've used on several
sites. It checks to
>>> see if
>>> the image needs to be resized, and if so, it
does the math to figure
>>> out the
>>> new proportional dimensions, whether you need to
resize to a
>>> specified width
>>> or to a specified height.
>>> $size = getimagesize($file);
>>> // Specify desired maximum dimensions
>>> $maxwidth = 650;
>>> $maxheight = 500;
>>> if ( ($size[0] <= $maxwidth) &&
($size[1] <= $maxheight) ) {
>>> // The image is the right size already
>>> $targetwidth = $size[0];
>>> $targetheight = $size[1];
>>> } else {
>>> // if width > height
>>> if ( $size[0] >= $size[1] ) { // if height
> width
>>> $targetwidth = $maxwidth;
>>> $targetheight = $targetwidth * ($size[1] /
$size[0]);
>>> } elseif ($size[1] > $size[0]) { // if height
> width
>>> $targetheight = $maxheight;
>>> $targetwidth = $targetheight * ($size[0] /
$size[1]);
>>> }
>>> } // END ELSE
>>>
>>> Now you have your target width and target height
set proportionally,
>>> and you
>>> can proceed with your resizing operation, using
$targetwidth and
>>> $targetheight.
>>>
>>
>>
>
>
seb ( [email protected])
http://webtrans1.com | high-end web
design
Downloads: Slide Show, Directory Browser, Mailing List

Similar Messages

  • Is there a way to change the master text length in FCP? The default length is 10 seconds, which is too long. I can easily adjust the length but I don't want to do it each time, and I don't want to adjust one and then have to copy and paste this length.

    Is there a way to change the master text length in FCP? The default length is 10 seconds, which is too long. I can easily adjust the length but I don't want to do it each time, and I don't want to adjust a text clip and then have to copy and paste this each time. Ideally, there should be something in User Preferences but there is not. Thanks.

    Maybe some one else can pipe up with a solution, but this would literally take 2 seconds to do for a new project.  And you can create a "template project" that includes this "text" clip.  Save this project and then to a get info and check "stationary pad."  When you double click on this file, fcp will open with a copy of this project and you just need to do a save as. 
    I've been working with computer editing systems for longer than i can remember and at a certain point you just have to adapt your workflow to the limitations of the software.  

  • Too much contrast, I can not see the light pantone on Illustrator

    Since a few days my screen is too much contrast, I can not see the light of pantones Illustrator

    Check the "Enhance Contrast" slider in Accessibility or Universal Access system preference.

  • HAVING TROUBLE SAVING ITEMS IN LION AS IT IS DIFFERENT THAN SNOW LEAPORD... CAN ANYONE SHARE THE CORRECT PROCEEDURE?

    I'M HAVING TROUBLE USING THE SAVE FEATURE IN LION AS IT'S MUCH DIFFERENT THAN THAT IN SNOW LEAPORD, CAN ANYONE SHARE THE CORRECT PROCEEDURE TO SAVE A DOCUMENT?

    Revert back to Snow Leopard would be the ideal choice.
    Not writing in all caps would be nice too, it's SHOUTING
    Thirdly, Lion introduced auto-save, so you have to duplicate the file, then open the duplicate to make changes.
    Wonderfully asinine.
    Quit the program, it will ask you to save.

  • Javaws can't lauch the corrected jnlp application

    (1)My jre,jdk version is 1506,javaws can't lauch the corrected jnlp application,and run javaws will popup a little window(java lauch),but after a few seconds it will auto exit,can't lauch the javaws view window,,
    (2)I run javacpl.exe and go to delete the cache fiile,which will throw "Bad installation. Error invoking Java VM (execv)",then I try uninstall all JDK and JRE,,and check the regedit javasoft,their have no 1506.
    (3)reintalled JDK JRE 1506,but the problem still exist. javaws can't lacuch application.
    (4)The problem maybe is I hava installed another version of JRE1510,but when the problem occur,I hava uninstalled all related JDK and JRE,,
    (5)I seached many thread,suggestion is uninstall and install the lastest version of jre,then I do it,uninstall All JDK,JRE,installed 1607,
    So bad,problem still exist.
    any body can help me break out this bad thing,they will get my the best benediction.
    Kevin

    Hi Kevin,
    how did you fix this? We´re experiencing the same problem. Web Start refuses to start any ws-application on some of our computers. De- and re-installing JREs or JDKs didn't help.

  • Whenever I update my iPhone software, it asks me to sign in to iCloud with an old email address.  My other devices all have the correct address.  How can I get the correct address for my iPhone?  The only Apple ID that works for logging in is my new one.

    Whenever I update my iPhone software, it asks me to sign in to iCloud with an old email address.  My other devices all have the correct address.  How can I get the correct address for my iPhone?  The only Apple ID that works for logging in is my new one.

    To change the iCloud ID you have to go to Settings>iCloud, tap Delete Account, provide the password for the old ID when prompted to turn off Find My iPhone (if you're using iOS 7), then sign back in with the ID you wish to use.  If you don't know the password for your old ID, or if it isn't accepted, go to https//appleid.apple.com, click Manage my Apple ID and sign in with your current iCloud ID.  Tap edit next to the primary email account, tap Edit, change it back to your old email address and save the change.  Then edit the name of the account to change it back to your old email address.  You can now use your current password to turn off Find My iPhone on your device, even though it prompts you for the password for your old account ID. Then go to Settings>iCloud, tap Delete Account and choose Delete from My iDevice when prompted (your iCloud data will still be in iCloud).  Next, go back to https//appleid.apple.com and change your primary email address and iCloud ID name back to the way it was.  Now you can go to Settings>iCloud and sign in with your current iCloud ID and password.

  • I have a Firewire 800 external hard drive and need to connect to my new MacBook Air.  Where can I get the correct cable?

    I have a Firewire 800 external hard drive and need to connect to my new MacBook Air.  Where can I get the correct cable?

    Apple has announced a Thunderbolt to Firewire adapter, but not yet given a release date.

  • Photoshop CC: Can't use the 3d function???

    Hello,
    I need help one this. I can't use the 3d function in photoshop cc and it gives me this error:
    http://i.imgur.com/Zn7e47d.png
    And here are my performance settings:
    http://i.imgur.com/A8rCi8J.png
    And here is the vram of my gpu:
    http://i.imgur.com/sSr5Knb.png
    And here is the paste from the system info thing:
    0bin - encrypted pastebin
    Ohh and i use windows 7 ultimate
    Anyone knows a fix for this as i can't live without
    Thanks!
    Regards,

  • I have a MacBook, made in 2010. I can't get the eject function to work. I have a DVD in now and want to eject it and put another one in. Command-E, dragging it to the trash or Find-Eject does not work. Ideas?

    I have a MacBook, made in 2010. I can't get the eject function to work. I have a DVD in now and want to eject it and put another one in. Command-E, dragging it to the trash or Find-Eject does not work. Ideas?

    Hi there. Hear are some other options . Hold down for click on the track pad while restarting and keep it down all the way thru boot. Or use right click on a mouse. If it's stuck, sometimes sticking a business card in top edge of slot while trying the eject option can work.

  • How can I Locate the correct filepath in a jsp page?

    In http://localhost:8080/myweb/a.jsp, I will call a java bean file which is locate in http://localhost:8080/myweb/WEB-INF/classes/haha/DBConnection.class. This java file requires to read an external file which locates in http://localhost:8080/myweb/WEB-INF/classes/haha/db.txt
    My question is how can I get the correct filepath in this environment?
    inputStream = new BufferedReader(new FileReader(????????));
    Only this will work
    inputStream = new BufferedReader(new FileReader("D:\Program Files\Apache Software Foundation\Tomcat 5.5\db.txt"));
    But no one will place the file here, and it is impossible to do this when upload to 3rd party hosting.
    Any suggestion? thx.

    Thx all, in a jsp page, calling this method is fine.
    ServletContext s = getServletContext();
    String a = s.getRealPath("/");
    In a Servlet file, below method is ready to use:
    String b = getServletConfig().getServletContext().getRealPath("/");
    My problem is, I have a jsp page, which initialize a java bean , this java file is responsible for Database Connection, which will read the external text file to get the login, password and database name. So I won't need to recompile this file every time when I place in different platform with different configuration. I only need to edit the text file is ok.
    But How can I get the absolute file path when that jsp page initialize that java bean file? Below is my error, any suggestions are thx.
    package sql;
    import java.sql.*;
    import java.util.ArrayList;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class DBConnection extends HttpServlet{
    public String sql = null;
    public Connection con = null;
    public Statement statement = null;
    public ResultSet rs = null;
    private BufferedReader inputStream = null;
    private static ArrayList<String> arr = new ArrayList<String>();
      public DBConnection(){
        String fs = System.getProperty("file.separator");
        ServletContext s = getServletContext();
        String realpath = s.getRealPath("/");
        String filepath = realpath + "WEB-INF"+fs+"Properties"+fs+"db.txt";
        try{
          inputStream = new BufferedReader(new FileReader(filepath));
          String l;
          while ((l = inputStream.readLine()) != null) {
            arr.add(l);
          Class.forName("com.mysql.jdbc.Driver");
          this.con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+arr.get(0)+"?user=" +arr.get(1)+ "&password="+arr.get(2)+"&useUnicode=true&characterEncoding=utf-8");
          this.statement = this.con.createStatement();
        }catch (Exception e){
          System.err.println(e.getMessage());
        }finally{
    }java.lang.NullPointerException
         javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
         sql.DBConnection.<init>(DBConnection.java:20)
         html.ShowCategory.<init>(ShowCategory.java:17)
         org.apache.jsp.left_jsp._jspService(left_jsp.java:66)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

  • Can't activate the COMPARE function for object DNL_CUST_TVAST for Adapter

    Hello
    I've applier OSS note 866824 to enable the exchange of the sales area flag deletion. I had to do the initial download for the customizing object DNL_CUST_TVAST but it failed because the no intial load was permitted as the data distribution was active. So I've applied note 887696 to enable the intial load for this object : I've deleted the COMPARE function for this object with transaction R3AC3. I've done the initial load for this object and now I can't add the COMPARE function : the error message is enter linked bdoc type for synchronisation load. and I don't know what to do...
    if somebody can help me...
    thanks a lot

    Thanks for your tip but it does not work, I need to fill this field.
    I just have an answer from SAP support, this value COMPARE is relevant for loading data in CDB.
    there no sense to add the compare value for this object : the compare load can never be used for this object. It was a delivery error
    Edited by: Jerome Munier on Dec 5, 2008 7:13 PM

  • TS3989 Can you use the search function in a shared photo stream? How?

    Can you use the search function in a shared photo stream? When I try to search in the shared photo stream it goes to search in my photos.

    I'm not sure there is a solution to your question, other than to not keep so many photos on your devices.  If you delete a photo from photo stream, it will delete it from all your devices.  To keep them, first save them to your camera roll (tap Edit, tap the photos, tap Share, tap Save to Camera Roll), then import them to your computer as explained here: http://support.apple.com/kb/HT4083.  However, given the number of photos you have, a much more practical solution would be to transfer them to your computer using an app like PhotoSync, which will select them all at once and transfer them over wifi.
    I'm not sure why you're seeing such a discrepancy in the amount of space taken up by your photos.  It's possible that something is corrupt given the large number of photos on your device.

  • I'm trying to delete multiple pix in iPhoto that i stupidly made duplicates of without knowing, I've tried going into the applications folder and using image capture but i think I've missed a step , can anyone send the correct info / steps pls thanks

    I'm trying to delete multiple pix in iPhoto that i stupidly made duplicates of without knowing, I've tried going into the applications folder and using image capture but i think I've missed a step , can anyone send the correct info / steps pls thanks

    again image capture is not involved with deleting photos from iPhoto in any way ever
    the paid version of iPhoto Library Manager is very good for finding duplicates as is Duplicate Annihilator
    And I have no idea who told you this - or what it means - but re-read both of my opening statements
    I was told I could delete multpiles thru image capture by transferring my iPhoto library etc
    LN

  • HT4046 why i can't enable the voiceOver function with my new labtop(window 7 64bits) with my ipod shuffle?

    why i can't enable the voiceOver function with my new labtop(window 7 64bits) with my ipod shuffle?

    even try to update the latest itunes but still can't fix it
    is it window's problem?
    it work fine in my orginal desktop with window XP
    PS: ipod shuffle 3rd

  • My current system is OS X 10.4.11 and I need a 10.5 to update my iPhone, where can I download the correct 10.5 update?

    My current system is OS X 10.4.11 and I need a 10.5 to update my iPhone, where can I download the correct 10.5 update?

    Hi, and welcome to Apple Support Communities.
    You can't download Mac OS X 10.5; you need to purchase it.
    Which exact iBook model is it?
    You can choose from this list:
    http://www.everymac.com/systems/apple/ibook/index-ibook.html
    Not all iBooks are compatible with Mac OS X 10.5, so we need to know which iBook you have.

Maybe you are looking for

  • Looking for a good laser printer for OSX 10.6.8

    I need a decent laser printer.  Using Macbook Pro with OSX 10.6.8.  I've given up trying to get the drivers to work on our office Xerox Workcentre 7328.  I keep getting the "OTC at end of life" error and I'm sick of trying to download drivers and try

  • File to File scenario is not working

    Hi I have done simple file to file scenario. I have done all the necessary cofigurations but XI is not picking the file I have checked in adapter monitoring its saying "File Adapter monitoring is now part of Channel Communication"  its not showing an

  • Cant load movies to apple tv

    I have a problem with my apple tv.. after i watch a movie, listen to a song etc from my itunes library, the thing i am trying to open wont open!! it just stayes with the loading screen forever. I then restart my apple tv and it works again for 1 movi

  • Adobe Shape for Android?

    Are there any plans on the Android version?

  • Dictation isn't very accurate on MacBook Pro - my iPad does much better

    Dictation isn't very accurate on MacBook Pro - my iPad does much better. Is anyone else having the same issues ?