简体   繁体   中英

Resize and rename PNG, JPG or GIF file with PHP

is there any way, using PHP, that you can resize an image sent from a HTML form's WIDTH (Only PNG, JPG and GIF) to a max value of let's say 500px (so if the file is 350px wide there isn't any stretching), and rename it to a random 15 character name (eg "e19gy675jo5el7g.png") and save it to the image/ directory?

I have some code already but it doesn't resize the file and allows all file types to be uploaded (it only renames the file to a random name). I don't want to use the accept="image/*" HTML code in the form so if you could help me find a PHP solution that would be great.

Here's my PHP code...

    <?php
 function findexts ($filename) 
 { 
 $filename = strtolower($filename) ; 
 $exts = split("[/\\.]", $filename) ; 
 $n = count($exts)-1; 
 $exts = $exts[$n]; 
 return $exts; 
 }     
 $ext = findexts ($_FILES['uploaded']['name']) ;   
 $ran = rand () ;   
 $ran2 = $ran.".";   
 $target = "image/";
 $target = $target . $ran2.$ext;   
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
 {
 echo "The file has been uploaded as ".$ran2.$ext;
 } 
 else
 {
 echo "Sorry, there was a problem uploading your file.";
 }
 ?> 

And here's my HTML

<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<div>
<input name="uploaded" type="file" />
</div>
<br>
<button type="submit">Upload</button>
</form>
</body>
</html>

Sorry for the complicated question, I'm just quite new with PHP :-)

Thanks in advance :-)

I don't know the whole code but you can do it by GD library of PHP.Use

getimagesize($filename)

TO get the image details and check the width using it.If width is less than 500 then do not resize.

Link that may help you: http://forums.phpfreaks.com/topic/210603-uploaded-image-change-width-and-height/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM