Asked  7 Months ago    Answers:  5   Viewed   27 times

I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?

Thanks!

 Answers

81

Ok, so below is an Image object that I use in my store. It maintains scale - requires GD

<?php
class Store_Model_Image extends My_Model_Abstract 
{
    const PATH  = STORE_MODEL_IMAGE_PATH;
    const URL   = "/store-assets/product-images/";

    public function get_image_url($width, $height)
    {
        $old_file = self::PATH . $this->get_filename();
        $basename = pathinfo($old_file, PATHINFO_FILENAME);

        $new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
        if(file_exists(self::PATH . $new_name))
        {
            return self::URL . $new_name;
        }
        else
        {
            list($width_orig, $height_orig, $image_type) = @getimagesize($old_file);
            $img = FALSE;

            // Get the image and create a thumbnail     
            switch($image_type)
            {
                case 1:
                    $img = @imagecreatefromgif($old_file);
                    break;
                case 2:
                    $img = @imagecreatefromjpeg($old_file);
                    break;
                case 3: 
                    $img = @imagecreatefrompng($old_file);
                    break;
            }

            if(!$img)
            {
                throw new Zend_Exception("ERROR: Could not create image handle from path.");
            }

            // Build the thumbnail
            if($width_orig > $height_orig)
            {
                $width_ratio = $width / $width_orig;
                $new_width   = $width;
                $new_height  = $height_orig * $width_ratio;
            }
            else
            {
                $height_ratio = $height / $height_orig;
                $new_width    = $width_orig * $height_ratio;
                $new_height   = $height;
            }

            $new_img = @imagecreatetruecolor($new_width, $new_height);

            // Fill the image black
            if(!@imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
            {           
                throw new Zend_Exception("ERROR: Could not fill new image");
            }

            if(!@imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
            {
                throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
            }

            // Use a output buffering to load the image into a variable
            ob_start();
            imagejpeg($new_img, NULL, 100);
            $image_contents = ob_get_contents();
            ob_end_clean();

            // lastly (for the example) we are writing the string to a file
            $fh = fopen(self::PATH . $new_name, "a+");
            fwrite($fh, $image_contents);
            fclose($fh);

            return self::URL . $new_name;
        }
    }
}

I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)

So in the template you pass your image object, and when you need a image thumb,

<img src="<?php echo $image->get_image_url(100, 100); ?>" />

you now have a 100x100 thumb, which is saved to the Server for reuse at a later date

Wednesday, March 31, 2021
 
csi
answered 7 Months ago
csi
49

The solution was the following:

    if ($width/$height > $this->maxWidth/$this->maxHeight) {
      // then resize to the new height...
                $command .= ' -resize "x'.$this->maxHeight.'"';

                // ... and get the middle part of the new image
                // what is the resized width?
                $resized_w = ($this->maxHeight/$height) * $width;

                // crop
                $command .= ' -crop "'.$this->maxWidth.'x'.$this->maxHeight.'+'.round(($resized_w - $this->maxWidth)/2).'+0" +repage';
            } else {
              $command .= ' -resize "' . $this->maxWidth . 'x"';
              $resized_h = ($this->maxWidth/$width) * $height;

                // crop
                $command .= ' -crop "'.$this->maxWidth.'x'.$this->maxHeight.
                             '+0+'.round(($resized_h - $this->maxHeight)/2).'" +repage';
            }
Saturday, May 29, 2021
 
gMale
answered 5 Months ago
36

Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.

$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

copy($_FILES, $resizedDestination);

$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];

$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

$originalImage = imageCreateFromJPEG($image);

$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);

imageDestroy($originalImage);
imageDestroy($resizedImage);

To anyone else seeking a complete example, create two files:

<!-- send.html -->

<html>

<head>

    <title>Simple File Upload</title>

</head>

<body>

    <center>

        <div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">

            Select an image.

            <br/>
            <br/>

            <form action="receive.php" enctype="multipart/form-data" method="post">
                <input type="file" name="image" size="40">
                <input type="submit" value="Send">
            </form>

        </div>

    </center>

</body>

<?php

// receive.php

$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";

echo "File path:".$filePath."<br/>";

if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {

    echo "File successfully received through HTTP POST.<br/>";

    // Validate the file size, accept files under 5 MB (~5e+6 bytes).

    if ($_FILES['image']['size'] <= 5000000) {

        echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";

        // Resize and save the image.

        $image = $_FILES["image"]["tmp_name"];
        $resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

        copy($_FILES, $resizedDestination);

        $imageSize = getImageSize($image);
        $imageWidth = $imageSize[0];
        $imageHeight = $imageSize[1];

        $DESIRED_WIDTH = 100;
        $proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

        $originalImage = imageCreateFromJPEG($image);

        $resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

        imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
        imageJPEG($resizedImage, $resizedDestination);

        imageDestroy($originalImage);
        imageDestroy($resizedImage);

        // Save the original image.

        if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {

            echo "Copied the original file to the specified destination.<br/>";

        }

    }

}

?>
Wednesday, June 9, 2021
 
Crontab
answered 5 Months ago
71

Override must be accessed via RequestOptions in the most recent version of Glide 4.x. You can add RequestOptions through apply()

Glide
    .with(context)
    .load(path)
    .apply(new RequestOptions().override(600, 200))
    .into(imageViewResizeCenterCrop);
Monday, August 2, 2021
 
Kevin
answered 3 Months ago
95

I would lean towards ImageMagick as far as image quality goes. It seems to produce considerably sharper/higher-quality images than GD2 (at the expense of larger filesize.)

ImageMagick is also not bound by PHP's memory limit.

Monday, August 9, 2021
 
nighter
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :