• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 676
  • Last Modified:

resampling image with GD LIbrary

What is the GD Library script to resample an image to 100 pixels tall in good quality?
0
weikelbob
Asked:
weikelbob
  • 3
  • 3
1 Solution
 
Brian BushSolutions ArchitectCommented:
<?php
  $_src = imagecreatefromjpeg("C:\DSCN1311.JPG");
  if($_src) {
      $_sw = imagesx($_src);
      $_sh = imagesy($_src);

      $_dw = 100; // Largest target dimension
      $_dh = ($_sh / $_sw) * $_dw;
      $_dest = imagecreatetruecolor($_dw,$_dh);
      imagecopyresampled($_dest, $_src, 0, 0, 0, 0, $_dw, $_dh, $_sw, $_sh);

      imagejpeg($_dest, "c:\out.jpg", 75);
      imagedestroy($_src);
      imagedestroy($_dest);
  }
?>
0
 
weikelbobAuthor Commented:
Great. Can I check to see if it's a GIF and do something else in that case?  The max height should be 100px

Thanks.
0
 
Brian BushSolutions ArchitectCommented:
You can use imagecreatefromgif and it works fine.

You can swap the $_dh and $_dw for the 100px height.
--brian
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
weikelbobAuthor Commented:
How do I test to see if it's a gif or jpg, then run the appropriate script?

Thanks for the good script, BTW.
0
 
Brian BushSolutions ArchitectCommented:
Try this code:

<?php

$_inFile = "C:\before-after.jpg";
$_info = getimagesize($_inFile);

$_outFile = "C:\imageOut";

if ($_info[2] == IMG_JPG) {
    $_src = imagecreatefromjpeg($_inFile);
} elseif ($_info[2] == IMG_GIF) {
    $_src = imagecreatefromgif($_inFile);
} else {
      echo "You can add other types later, but right its just GIF and JPG.";
}

if($_src) {
    $_dh = 100;
    $_dw = ($_info[0] / $_info[1]) * $_dh;
    $_dest = imagecreatetruecolor($_dw,$_dh);
    imagecopyresampled($_dest, $_src, 0, 0, 0, 0, $_dw, $_dh, $_info[0], $_info[1]);

    if ($_info[2] == IMG_JPG) {
        imagejpeg($_dest, $_outFile . ".jpg", 75);
    } elseif ($_info[2] == IMG_GIF) {
        imagegif($_dest, $_outFile . ".gif", 75);
    } else {
          echo "You can add other types later, but right its just GIF and JPG.";
    }

    imagedestroy($_src);
    imagedestroy($_dest);
}
?>


--brian
0
 
weikelbobAuthor Commented:
Brian,

I'm still implimenting this.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now