Переименовать файл изображения при загрузке php - PullRequest
2 голосов
/ 06 января 2011

У меня есть форма для загрузки изображения.Index.html отправляет данные в resizer.php.Кодировка выглядит следующим образом:

index.html

<form action="resizer.php" method="post" enctype="multipart/form-data">
    Image: <input type="file" name="file" />
    <input type="submit" name="submit" value="upload" />
</form>

resizer.php

<?php
require_once('imageresizer.class.php');
$imagename = "myimagename";

//Path To Upload Directory
$dirpath = "uploaded/";

//MAX WIDTH AND HEIGHT OF IMAGE
$max_height = 100;
$max_width = 100;

//Create Image Control Object - Parameters(file name, file tmp name, file type, directory path)
$resizer = new ImageResizer($_FILES['file']['name'],$_FILES['file']['tmp_name'],$dirpath);

//RESIZE IMAGE - Parameteres(max height, max width)
$resizer->resizeImage($max_height,$max_width);

//Display Image
$resizer->showResizedImage();


?>

imageresizer.class.php

<?php

    class ImageResizer{
        public $file_name;
        public $tmp_name;
        public $dir_path;




        //Set variables
        public function __construct($file_name,$tmp_name,$dir_path){
            $this->file_name = $file_name;
            $this->tmp_name = $tmp_name;
            $this->dir_path = $dir_path;
            $this->getImageInfo();
            $this->moveImage();
        }
        //Move the uploaded image to the new directory and rename
        public function moveImage(){
            if(!is_dir($this->dir_path)){
                mkdir($this->dir_path,0777,true);
            }
            if(move_uploaded_file($this->tmp_name,$this->dir_path.$this->file_name)){
                $this->setFileName($this->dir_path.$this->file_name);
            }

        }

        //Define the new filename
        public function setFileName($file_name){
            $this->file_name = $file_name;
            return $this->file_name;
        }

        //Resize the image function with new max height and width
        public function resizeImage($max_height,$max_width){
            $this->max_height = $max_height;
            $this->max_width = $max_width;

            if($this->height > $this->width){
                $ratio = $this->height / $this->max_height;
                $new_height = $this->max_height;
                $new_width = ($this->width / $ratio);
            }
            elseif($this->height < $this->width){
                $ratio = ($this->width / $this->max_width);
                $new_width = $this->max_width;
                $new_height = ($this->height / $ratio);
            }
            else{
                $new_width = $this->max_width;
                $new_height = $this->max_height;
            }


            $thumb = imagecreatetruecolor($new_width, $new_height);

            switch($this->file_type){
                case 1:
                    $image = imagecreatefromgif($this->file_name);
                    break;
                case 2:
                    $image = imagecreatefromjpeg($this->file_name);
                    break;
                case 3:
                    $image = imagecreatefrompng($this->file_name);
                    break;
                case 4:
                    $image = imagecreatefromwbmp($this->file_name);
            }

            imagecopyresampled($thumb, $image, 0, 0, 0, 0, $new_width, $new_height, $this->width, $this->height);

            switch($this->file_type){
                case 1:
                    imagegif($thumb,$this->file_name);
                    break;
                case 2:
                    imagejpeg($thumb,$this->file_name,100);
                    break;
                case 3:
                    imagepng($thumb,$this->file_name,0);
                    break;
                case 4:
                    imagewbmp($thumb,$this->file_name);
            }

            imagedestroy($image);
            imagedestroy($thumb);
        }

        public function getImageInfo(){
            list($width, $height, $type) = getimagesize($this->tmp_name);
            $this->width = $width;
            $this->height = $height;
            $this->file_type = $type;

        }

        public function showResizedImage(){
            echo "<img src='".$this->file_name." />";
        }


        public function onSuccess(){
            header("location: index.php");
        }

    }
?>

Все работает хорошо .. Файл загружается с его оригинальным именем файла.Но я хочу переименовать файл в «myimagename», который является переменной в resizer.php.Как я могу сделать это возможным?

Заранее спасибо ...:)

blasteralfred

Ответы [ 4 ]

2 голосов
/ 06 января 2011

Попробуйте это:

    public function moveImage(){
        global $imagename;
        if(!is_dir($this->dir_path)){
            mkdir($this->dir_path,0777,true);
        }
        if(move_uploaded_file($this->tmp_name,$this->dir_path.$imagename)){
            $fileParts = explode('.', $this->tmp_name);
            $this->setFileName($this->dir_path.$imagename.'.'.$fileParts[count($fileParts)-1]);
        }

    }

Редактировать: Добавлено расширение для вас; -)

0 голосов
/ 31 августа 2015

</p> <pre><code>class ImageResizer{ public $file_name; public $tmp_name; public $dir_path; //Set variables public function __construct($file_name,$tmp_name,$dir_path){ $this->file_name =$foto = $dir.rand(00,999).date("-Y-m-d_H-i-s").$file_name; $this->tmp_name = $tmp_name; $this->dir_path = $dir_path; $this->getImageInfo(); $this->moveImage(); $sql="insert into foto (foto) values ('".$this->file_name."')"; mysql_query($sql); } //Move the uploaded image to the new directory and rename public function moveImage(){ if(!is_dir($this->dir_path)){ mkdir($this->dir_path,0777,true); } if(move_uploaded_file($this->tmp_name,$this->dir_path.$this->file_name)){ $this->setFileName($this->dir_path.$this->file_name); rename($this->file_name, $imagename ); } } //Define the new filename public function setFileName($file_name){ $this->file_name = $file_name; return $this->file_name; } //Resize the image function with new max height and width public function resizeImage($max_height,$max_width){ $this->max_height = $max_height; $this->max_width = $max_width; if($this->height > $this->width){ $ratio = $this->height / $this->max_height; $new_height = $this->max_height; $new_width = ($this->width / $ratio); } elseif($this->height < $this->width){ $ratio = ($this->width / $this->max_width); $new_width = $this->max_width; $new_height = ($this->height / $ratio); } else{ $new_width = $this->max_width; $new_height = $this->max_height; } $thumb = imagecreatetruecolor($new_width, $new_height); switch($this->file_type){ case 1: $image = imagecreatefromgif($this->file_name); break; case 2: $image = imagecreatefromjpeg($this->file_name); break; case 3: $image = imagecreatefrompng($this->file_name); break; case 4: $image = imagecreatefromwbmp($this->file_name); } imagecopyresampled($thumb, $image, 0, 0, 0, 0, $new_width, $new_height, $this->width, $this->height); switch($this->file_type){ case 1: imagegif($thumb,$this->file_name); break; case 2: imagejpeg($thumb,$this->file_name,100); break; case 3: imagepng($thumb,$this->file_name,0); break; case 4: imagewbmp($thumb,$this->file_name); } imagedestroy($image); imagedestroy($thumb); } public function getImageInfo(){ list($width, $height, $type) = getimagesize($this->tmp_name); $this->width = $width; $this->height = $height; $this->file_type = $type; } public function showResizedImage(){ echo "<img src='".$this->file_name." />"; } public function onSuccess(){ header("location: index.php"); } }

0 голосов
/ 29 декабря 2013
<form action="<?php echo $_server['php-self'];  ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm"> 
        <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" /> 
        <button name="submit" type="submit" class="submitButton">Upload Image</button> 
</form> 
<?php 
        if(isset($_POST['submit'])){ 
          if (isset ($_FILES['new_image'])){ 
              $imagename = $_FILES['new_image']['name']; 
              $source = $_FILES['new_image']['tmp_name']; 
              $target = "./temp/".$imagename; 
              move_uploaded_file($source, $target); 

              $imagepath = $imagename; 
              $save = "./temp/" . $imagepath; //This is the new file you saving 
              $file = "./temp/" . $imagepath; //This is the original file 

              list($width, $height) = getimagesize($file) ;  

              $modwidth = 500;  

              $diff = $width / $modwidth; 

              $modheight = $height / $diff;  
              $tn = imagecreatetruecolor($modwidth, $modheight) ;  
              $image = imagecreatefromjpeg($file) ;  
              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;  

              imagejpeg($tn, $save, 100) ;  

              $i=123;
              $j='.jpg';

              $save = "./images/".$i .$imagepath; //This is the new file you saving 
              $file = "./temp/" . $imagepath; //This is the original file 

              list($width, $height) = getimagesize($file) ;  

              $modwidth = 160;  

              $diff = $width / $modwidth; 

              $modheight = $height / $diff;  
              $tn = imagecreatetruecolor($modwidth, $modheight) ;  
              $image = imagecreatefromjpeg($file) ;  
              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;  

              imagejpeg($tn, $save, 100) ; 
              unlink($target); //Delete our uploaded file
            echo "Large image: <img src='./temp/".$imagepath."'><br>";  
            echo "Small image: <img src='./images/".$i .$imagepath; echo"'>";  
            echo " <br> Large image path: './temp/".$imagepath;  
            echo " <br> Small image path: './images/".$i .$imagepath;  

          } 
        } 

?>
0 голосов
/ 06 января 2011
//Create Image Control Object - Parameters(file name, file tmp name, file type, directory path)
$resizer = new ImageResizer($_FILES['file']['name'],$_FILES['file']['tmp_name'],$dirpath);

// Rename
$resizer->setFileName('new_file_name.jpg');

//RESIZE IMAGE - Parameteres(max height, max width)
$resizer->resizeImage($max_height,$max_width);
...