Изменение размера изображений на PHP без использования сторонних библиотек?

В одном из моих приложений я использую фрагмент кода ниже, чтобы скопировать загруженные изображения в каталог. Он отлично работает, но копирование больших изображений (> 2 МБ) занимает больше времени, чем идеально, и мне действительно не нужны изображения, большие, поэтому я ищу способ изменить размер изображений. Как добиться этого с помощью PHP?

<?php $uploadDirectory = 'images/0001/'; $randomNumber = rand(0, 99999); $filename = basename($_FILES['userfile']['name']); $filePath = $uploadDirectory.md5($randomNumber.$filename); // Check if the file was sent through HTTP POST. if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) { // Validate the file size, accept files under 5 MB (~5e+6 bytes). if ($_FILES['userfile']['size'] <= 5000000) { // Move the file to the path specified. if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) { // ... } } } ?> 

Наконец, я обнаружил способ, который соответствует моим потребностям. Следующий фрагмент изменяет размер изображения до указанной ширины, автоматически вычисляя высоту, чтобы сохранить пропорцию.

 $image = $_FILES["image"]["tmp_name"]; $resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg"; copy($_FILES, $resizedDestination); $imageSize = getImageSize($image); $imageWidth = $imageSize[0]; $imageHeight = $imageSize[1]; $DESIRED_WIDTH = 100; $proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth); $originalImage = imageCreateFromJPEG($image); $resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight); imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight); imageJPEG($resizedImage, $resizedDestination); imageDestroy($originalImage); imageDestroy($resizedImage); 

Для всех, кто ищет полный пример, создайте два файла:

 <!-- send.html --> <html> <head> <title>Simple File Upload</title> </head> <body> <center> <div style="margin-top:50px; padding:20px; border:1px solid #CECECE;"> Select an image. <br/> <br/> <form action="receive.php" enctype="multipart/form-data" method="post"> <input type="file" name="image" size="40"> <input type="submit" value="Send"> </form> </div> </center> </body> 

 <?php // receive.php $randomNumber = rand(0, 99999); $uploadDirectory = "images/"; $filename = basename($_FILES['file_contents']['name']); $destination = $uploadDirectory.md5($randomNumber.$filename).".jpg"; echo "File path:".$filePath."<br/>"; if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) { echo "File successfully received through HTTP POST.<br/>"; // Validate the file size, accept files under 5 MB (~5e+6 bytes). if ($_FILES['image']['size'] <= 5000000) { echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>"; // Resize and save the image. $image = $_FILES["image"]["tmp_name"]; $resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg"; copy($_FILES, $resizedDestination); $imageSize = getImageSize($image); $imageWidth = $imageSize[0]; $imageHeight = $imageSize[1]; $DESIRED_WIDTH = 100; $proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth); $originalImage = imageCreateFromJPEG($image); $resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight); imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight); imageJPEG($resizedImage, $resizedDestination); imageDestroy($originalImage); imageDestroy($resizedImage); // Save the original image. if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) { echo "Copied the original file to the specified destination.<br/>"; } } } ?> 

Я сделал функцию для изменения размера изображения наполовину, код ниже.

  function imgResize($path) { $x = getimagesize($path); $width = $x['0']; $height = $x['1']; $rs_width = $width / 2;//resize to half of the original width. $rs_height = $height / 2;//resize to half of the original height. switch ($x['mime']) { case "image/gif": $img = imagecreatefromgif($path); break; case "image/jpg": case "image/jpeg": $img = imagecreatefromjpeg($path); break; case "image/png": $img = imagecreatefrompng($path); break; } $img_base = imagecreatetruecolor($rs_width, $rs_height); imagecopyresized($img_base, $img, 0, 0, 0, 0, $rs_width, $rs_height, $width, $height); $path_info = pathinfo($path); switch ($path_info['extension']) { case "gif": imagegif($img_base, $path); break; case "jpg": case "jpeg": imagejpeg($img_base, $path); break; case "png": imagepng($img_base, $path); break; } } 

и вы сможете вызвать функцию ниже.

 $img = imgResize('c:/dir/image.png'); 

существует 1 очень простая функция изменения размера изображения для всех типов изображений, которые сохраняют прозрачность и очень просты в использовании

проверять, выписываться :

https://github.com/Nimrod007/PHP_image_resize

надеюсь это поможет

ImageMagick – самый быстрый и, вероятно, лучший способ изменить размер изображений на PHP. Ознакомьтесь с различными примерами здесь . В этом примере показано, как изменять размер и изображение при загрузке .

Вы также можете использовать метод x * y / width для изменения размера, а затем вызов imagecopyresampled (), как показано на http://www.virtualsecrets.com/upload-resize-image-php-mysql.html Эта страница также помещает изображения ( после изменения размера) в mySQL через PDO.

Спасибо Mateus Nunes! я отредактировал его работу немного, чтобы получить прозрачные pngs, работающие:

 $source = $_FILES["..."]["tmp_name"]; $destination = 'abc/def/ghi.png'; $maxsize = 45; $size = getimagesize($source); $width_orig = $size[0]; $height_orig = $size[1]; unset($size); $height = $maxsize+1; $width = $maxsize; while($height > $maxsize){ $height = round($width*$height_orig/$width_orig); $width = ($height > $maxsize)?--$width:$width; } unset($width_orig,$height_orig,$maxsize); $images_orig = imagecreatefromstring( file_get_contents($source) ); $photoX = imagesx($images_orig); $photoY = imagesy($images_orig); $images_fin = imagecreatetruecolor($width,$height); imagesavealpha($images_fin,true); $trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127); imagefill($images_fin,0,0,$trans_colour); unset($trans_colour); ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); unset($photoX,$photoY,$width,$height); imagepng($images_fin,$destination); unset($destination); ImageDestroy($images_orig); ImageDestroy($images_fin); с $source = $_FILES["..."]["tmp_name"]; $destination = 'abc/def/ghi.png'; $maxsize = 45; $size = getimagesize($source); $width_orig = $size[0]; $height_orig = $size[1]; unset($size); $height = $maxsize+1; $width = $maxsize; while($height > $maxsize){ $height = round($width*$height_orig/$width_orig); $width = ($height > $maxsize)?--$width:$width; } unset($width_orig,$height_orig,$maxsize); $images_orig = imagecreatefromstring( file_get_contents($source) ); $photoX = imagesx($images_orig); $photoY = imagesy($images_orig); $images_fin = imagecreatetruecolor($width,$height); imagesavealpha($images_fin,true); $trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127); imagefill($images_fin,0,0,$trans_colour); unset($trans_colour); ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); unset($photoX,$photoY,$width,$height); imagepng($images_fin,$destination); unset($destination); ImageDestroy($images_orig); ImageDestroy($images_fin); с $source = $_FILES["..."]["tmp_name"]; $destination = 'abc/def/ghi.png'; $maxsize = 45; $size = getimagesize($source); $width_orig = $size[0]; $height_orig = $size[1]; unset($size); $height = $maxsize+1; $width = $maxsize; while($height > $maxsize){ $height = round($width*$height_orig/$width_orig); $width = ($height > $maxsize)?--$width:$width; } unset($width_orig,$height_orig,$maxsize); $images_orig = imagecreatefromstring( file_get_contents($source) ); $photoX = imagesx($images_orig); $photoY = imagesy($images_orig); $images_fin = imagecreatetruecolor($width,$height); imagesavealpha($images_fin,true); $trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127); imagefill($images_fin,0,0,$trans_colour); unset($trans_colour); ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); unset($photoX,$photoY,$width,$height); imagepng($images_fin,$destination); unset($destination); ImageDestroy($images_orig); ImageDestroy($images_fin); с $source = $_FILES["..."]["tmp_name"]; $destination = 'abc/def/ghi.png'; $maxsize = 45; $size = getimagesize($source); $width_orig = $size[0]; $height_orig = $size[1]; unset($size); $height = $maxsize+1; $width = $maxsize; while($height > $maxsize){ $height = round($width*$height_orig/$width_orig); $width = ($height > $maxsize)?--$width:$width; } unset($width_orig,$height_orig,$maxsize); $images_orig = imagecreatefromstring( file_get_contents($source) ); $photoX = imagesx($images_orig); $photoY = imagesy($images_orig); $images_fin = imagecreatetruecolor($width,$height); imagesavealpha($images_fin,true); $trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127); imagefill($images_fin,0,0,$trans_colour); unset($trans_colour); ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); unset($photoX,$photoY,$width,$height); imagepng($images_fin,$destination); unset($destination); ImageDestroy($images_orig); ImageDestroy($images_fin); с $source = $_FILES["..."]["tmp_name"]; $destination = 'abc/def/ghi.png'; $maxsize = 45; $size = getimagesize($source); $width_orig = $size[0]; $height_orig = $size[1]; unset($size); $height = $maxsize+1; $width = $maxsize; while($height > $maxsize){ $height = round($width*$height_orig/$width_orig); $width = ($height > $maxsize)?--$width:$width; } unset($width_orig,$height_orig,$maxsize); $images_orig = imagecreatefromstring( file_get_contents($source) ); $photoX = imagesx($images_orig); $photoY = imagesy($images_orig); $images_fin = imagecreatetruecolor($width,$height); imagesavealpha($images_fin,true); $trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127); imagefill($images_fin,0,0,$trans_colour); unset($trans_colour); ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); unset($photoX,$photoY,$width,$height); imagepng($images_fin,$destination); unset($destination); ImageDestroy($images_orig); ImageDestroy($images_fin); с $source = $_FILES["..."]["tmp_name"]; $destination = 'abc/def/ghi.png'; $maxsize = 45; $size = getimagesize($source); $width_orig = $size[0]; $height_orig = $size[1]; unset($size); $height = $maxsize+1; $width = $maxsize; while($height > $maxsize){ $height = round($width*$height_orig/$width_orig); $width = ($height > $maxsize)?--$width:$width; } unset($width_orig,$height_orig,$maxsize); $images_orig = imagecreatefromstring( file_get_contents($source) ); $photoX = imagesx($images_orig); $photoY = imagesy($images_orig); $images_fin = imagecreatetruecolor($width,$height); imagesavealpha($images_fin,true); $trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127); imagefill($images_fin,0,0,$trans_colour); unset($trans_colour); ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); unset($photoX,$photoY,$width,$height); imagepng($images_fin,$destination); unset($destination); ImageDestroy($images_orig); ImageDestroy($images_fin);