2016-03-14 49 views
0

您可以讓我知道如何在加載到服務器時重命名和更改擴展名的圖像文件?如何在PHP中重命名並更改上傳圖像的擴展名

我會做的是改變所選圖像擴展.jpg(從png格式或.JPEG)和硬編碼像new-image-1

的名字,現在我已經是這裏面究竟上傳圖像文件作爲原名稱和擴展名。

$sourcePath = $_FILES['file']['tmp_name']; 
$targetPath = "../uploads/".$_FILES['file']['name']; 
move_uploaded_file($sourcePath,$targetPath) ; 
+0

可能重複的[我怎樣才能使用PHP更改文件的擴展?](http://stackoverflow.com/questions/193794)/how-can-i-change-a-files-extension-using-php) – manniL

+0

如果你不想使用原始文件名,那麼你爲什麼要告訴php使用'$ targetPath = ...' ? 「我把雜貨放在櫃檯上,爲什麼櫃檯上有雜貨?我想把它們放在地板上」。 –

+0

Marc B,感謝您的回覆,那麼如何才能訪問原始文件呢? – Behseini

回答

0
$getName = $_FILES['file']['name']; 
$explodeName = explode(".", $getName); //splits by .(dot) 
$extention = strtowlower(end($explodeName)); //gets last splited value and returns extention 

explodeend使用能達到您的要求

更多地瞭解explodeend

與變化圖像extention此言.jpg

if (preg_match('/jpg|jpeg/i',$extention)) 
     $imageTmp=imagecreatefromjpeg($tempImagePath); 
    else if (preg_match('/png/i',$extention)) 
     $imageTmp=imagecreatefrompng($tempImagePath); 
    else if (preg_match('/gif/i',$extention)) 
     $imageTmp=imagecreatefromgif($tempImagePath); 
    else if (preg_match('/bmp/i',$extention)) 
     $imageTmp=imagecreatefrombmp($tempImagePath); 

你可以使用上面的代碼的任何圖像轉換爲jpg,並直接給予一個隨機的新名字串連與.jpg

+0

謝謝,但在這裏我只是得到文件擴展名!所以我該如何改變它? – Behseini

+0

更改爲什麼擴展? – ameenulla0007

+0

你沒讀過帖子?我需要在JPG – Behseini

0

Detemine它是通過檢查擴展名是什麼文件類型。

打開來自源位置的文件用的圖像GD庫函數:

http://php.net/manual/en/ref.image.php

$img = imagecreatefrompng($source);

然後保存圖像:

imagejpeg($img, $target.'.jpg');

也參見:

http://php.net/manual/en/function.imagejpeg.php

如果你只是想更換擴展用一樣的東西:

$target = str_replace('.jpg','.JPEG',$filename);

您只需重命名PNG爲JPG。雖然你可能會和瀏覽器可以修復它,但你不應該...

相關問題