2

我有许多图像被上传到具有随机文件名的站点,例如

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

是否有可能在 PHP 中以某种方式在 url 的文件扩展名(或)部分之前立即插入.jpg另一个.jpeg .png字符串.gif,例如-300x200

4

2 回答 2

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

这基本上是这样做的,从左到右阅读:

它替换以点 ( \.) 开头的任何内容,后跟+范围内的一个或多个 ( ) 字符,字符串a-z的末尾 ( $),不区分大小写 ( i),-300x200后跟字符串中刚刚匹配的部分 ( \0)。

于 2012-11-02T01:31:57.660 回答
1

如果您希望在上传图像时重命名文件名,下面的类将帮助您:

<?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 );
    }

?>

在哪里

      $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
于 2012-11-02T01:40:25.127 回答