2

I have a number of images being uploaded to a site with random file names e.g.

http://www.mysite.com/uploads/images/apicture23.jpg
http://www.mysite.com/uploads/images/anotherpicture203.jpeg
http://www.mysite.com/uploads/images/another.picture203.png
http://www.mysite.com/uploads/images/athird-picture101.gif

Is it possible in PHP to somehow insert immediately before the file extension (.jpg, .jpeg .png or .gif) part of the url another string such as -300x200 ?

2 Answers 2

5
$out = preg_replace('/\.[a-z]+$/i','-300x200\0',$in);

This basically does this, reading from left to right:

It replaces anything starting with a dot (\.), followed by one or more (+) characters in the range a-z, at the end ($) of the string, case-insensitive (i), by -300x200 followed by the part of the string just matched (\0).

Sign up to request clarification or add additional context in comments.

2 Comments

Please explain to the OP what this does and how it works, and link to documentation where appropriate.
I am positive that the top 1 hit in google on preg_replace will lead to the official php.net documentation.
1

If you wish to rename your file name when you upload the image, the bellowing class will help you:

<?php

    function thumbnail( $img, $source, $dest, $maxw, $maxh ) {      
        $jpg = $source.$img;

        if( $jpg ) {
            list( $width, $height  ) = getimagesize( $jpg ); //$type will return the type of the image
            $source = imagecreatefromjpeg( $jpg );

            if( $maxw >= $width && $maxh >= $height ) {
                $ratio = 1;
            }elseif( $width > $height ) {
                $ratio = $maxw / $width;
            }else {
                $ratio = $maxh / $height;
            }

            $thumb_width = round( $width * $ratio ); //get the smaller value from cal # floor()
            $thumb_height = round( $height * $ratio );

            $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
            imagecopyresampled( $thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height );

            $path = $dest.$img."-300x200.jpg";
            imagejpeg( $thumb, $path, 75 );
        }
        imagedestroy( $thumb );
        imagedestroy( $source );
    }

?>

Where

      $img         => image file name
      $source      => the path to the source image
      $dest        => the path to the destination image
      $maxw        => the maximum of the image width you desire
      $maxh        => the minimum one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.