web-dev-qa-db-fra.com

php redimensionner l'image lors du téléchargement

J'ai reçu un formulaire dans lequel l'utilisateur insère des données et télécharge également une image.

Pour traiter l'image, j'ai obtenu le code suivant:

define("MAX_SIZE", "10000");
$errors = 0;
$image = $_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
    $filename = stripslashes($_FILES['fileField']['name']);
    $extension = strtolower(getExtension($filename));
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")){
        echo ' Unknown Image extension ';
        $errors = 1;
    } else {
        $newname = "$product_cn.$extension";
        $size = filesize($_FILES['fileField']['tmp_name']);
        if ($size > MAX_SIZE*1024){
            echo "You have exceeded the size limit";
            $errors = 1;
        }
        if($extension == "jpg" || $extension == "jpeg" ){
            $uploadedfile = $_FILES['file']['tmp_name'];
            $src = imagecreatefromjpeg($uploadedfile);
        } else if($extension == "png"){
            $uploadedfile = $_FILES['file']['tmp_name'];
            $src = imagecreatefrompng($uploadedfile);
        } else {
            $src = imagecreatefromgif($uploadedfile);
        }
        list($width, $height) = getimagesize($uploadedfile);
        $newwidth = 60;
        $newheight = ($height/$width)*$newwidth;
        $tmp = imagecreatetruecolor($newwidth, $newheight);
        $newwidth1 = 25;
        $newheight1 = ($height/$width)*$newwidth1;
        $tmp1 = imagecreatetruecolor($newwidth1, $newheight1);
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagecopyresampled($tmp1, $src, 0, 0, 0, 0, $newwidth1, $newheight1, $width, $height);
        $filename = "../products_images/$newname";
        $filename1 = "../products_images/thumbs/$newname";
        imagejpeg($tmp, $filename, 100); // file name also indicates the folder where to save it to
        imagejpeg($tmp1, $filename1, 100);
        imagedestroy($src);
        imagedestroy($tmp);
        imagedestroy($tmp1);
    }
}

fonction getExtension:

function getExtension($str) {
    $i = strrpos($str, ".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
}

J'ai écrit des notes dans le code car je ne suis pas vraiment familiarisé avec ces fonctions.

Pour une raison quelconque, cela ne fonctionne pas. Lorsque je vais dans le dossier "product_images" ou "product_images/thumbs", je ne trouve aucune image téléchargée.

Une idée de ce qui ne va pas avec mon code? Il devrait y avoir une image de largeur 60px et une image de largeur 25px.

Remarque: Les variables pour lesquelles vous ne savez pas où elles ont été déclarées, telles que $product_cn ont été déclarés avant ce bloc de code qui fonctionne parfaitement (testé). Si vous souhaitez toujours y jeter un coup d'œil, n'hésitez pas à demander le code.

Merci d'avance!

29
kfirba

Vous pouvez utiliser cette bibliothèque pour manipuler l'image pendant le téléchargement. http://www.verot.net/php_class_upload.htm

25
Alok M. Kejriwal

Voici une autre solution simple et agréable:

$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
    $target_filename = $file_name;
    $ratio = $width/$height;
    if( $ratio > 1) {
        $new_width = $maxDim;
        $new_height = $maxDim/$ratio;
    } else {
        $new_width = $maxDim*$ratio;
        $new_height = $maxDim;
    }
    $src = imagecreatefromstring( file_get_contents( $file_name ) );
    $dst = imagecreatetruecolor( $new_width, $new_height );
    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    imagedestroy( $src );
    imagepng( $dst, $target_filename ); // adjust format as needed
    imagedestroy( $dst );
}

Référence: redimensionnement PHP proportionnel à la largeur ou au poids maximal

Edit: nettoyé et simplifié un peu le code. Merci @ jan-mirus pour votre commentaire.

39
zeusstl

// C’est mon exemple avec lequel j’ai utilisé pour redimensionner automatiquement chaque photo insérée à 100 x 50 pixels et le format d’image au format jpeg.

if($result){
$maxDimW = 100;
$maxDimH = 50;
list($width, $height, $type, $attr) = getimagesize( $_FILES['photo']['tmp_name'] );
if ( $width > $maxDimW || $height > $maxDimH ) {
    $target_filename = $_FILES['photo']['tmp_name'];
    $fn = $_FILES['photo']['tmp_name'];
    $size = getimagesize( $fn );
    $ratio = $size[0]/$size[1]; // width/height
    if( $ratio > 1) {
        $width = $maxDimW;
        $height = $maxDimH/$ratio;
    } else {
        $width = $maxDimW*$ratio;
        $height = $maxDimH;
    }
    $src = imagecreatefromstring(file_get_contents($fn));
    $dst = imagecreatetruecolor( $width, $height );
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );

    imagejpeg($dst, $target_filename); // adjust format as needed


}

move_uploaded_file($_FILES['pdf']['tmp_name'],"pdf/".$_FILES['pdf']['name']);
7
Edwinfad
<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>
<?php
    if(isset($_POST['submit'])){
      if (isset ($_FILES['new_image'])){


          $imagename = $_FILES['new_image']['name'];
          $source = $_FILES['new_image']['tmp_name'];
          $target = "images/".$imagename;
          $type=$_FILES["new_image"]["type"];

          if($type=="image/jpeg" || $type=="image/jpg"){

          move_uploaded_file($source, $target);
        //orginal image making part

          $imagepath = $imagename;
          $save = "images/" . $imagepath; //This is the new file you saving
          $file = "images/" . $imagepath; //This is the original file
          list($width, $height) = getimagesize($file) ;
          $modwidth = 1000;
          $diff = $width / $modwidth;
          $modheight = $height / $diff;   
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
          imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
          echo "Large image: <img src='images/".$imagepath."'><br>";                     
          imagejpeg($tn, $save, 100) ;

        //thumbnail image making part

          $save = "images/thumb/" . $imagepath; //This is the new file you saving
          $file = "images/" . $imagepath; //This is the original file   
          list($width, $height) = getimagesize($file) ;
          $modwidth = 150;
          $diff = $width / $modwidth;
          $modheight = $height / $diff;
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
          imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
        //echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
          imagejpeg($tn, $save, 100) ; 



          }
        else{
            echo "File is not image";
            }
      }
    }

?>

2
GURU WEB

Si vous voulez utiliser Imagick directement (inclus avec la plupart des distributions PHP)], c'est aussi simple que ...

$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);

$image->scaleImage(100,200,FALSE);

$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);

Vous voudrez probablement calculer la largeur et la hauteur de manière plus dynamique en fonction de l'image d'origine. Vous pouvez obtenir la largeur et la hauteur actuelles d'une image, en utilisant l'exemple ci-dessus, avec $ image-> getImageHeight (); et $ image-> getImageWidth () ;.

1
HoldOffHunger

Téléchargez le fichier de bibliothèque Zebra_Image.php belo link

https://drive.google.com/file/d/0Bx-7K3oajNTRV1I2UzYySGZFd3M/view

resizeimage.php

<?php
    require 'Zebra_Image.php';
    // create a new instance of the class
     $resize_image = new Zebra_Image();
     // indicate a source image
    $resize_image->source_path = $target_file1;
    $ext = $photo;
    // indicate a target image
    $resize_image->target_path = 'images/thumbnil/' . $ext;
    // resize
    // and if there is an error, show the error message
    if (!$resize_image->resize(200, 200, ZEBRA_IMAGE_NOT_BOXED, -1));
    // from this moment on, work on the resized image
    $resize_image->source_path = 'images/thumbnil/' . $ext;
?>
0
Pankaj Upadhyay

Cette chose a fonctionné pour moi. Aucune bibliothèque externe utilisée

    define ("MAX_SIZE","3000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["image-1"]["name"];
    $uploadedfile = $_FILES['image-1']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['image-1']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {
            echo "Unknown Extension..!";
        }
        else
        {

 $size=filesize($_FILES['image-1']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    echo "File Size Excedeed..!!";
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}

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


$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=1000;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);


$filename = "../images/product-image/Cars/". $_FILES['image-1']['name'];

$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];



imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}
0
user9290149

index.php:

<!DOCTYPE html>
<html>
<head>
    <title>PHP Image resize to upload</title>
</head>
<body>


<div class="container">
    <form action="pro.php" method="post" enctype="multipart/form-data">
        <input type="file" name="image" /> 
        <input type="submit" name="submit" value="Submit" />
    </form>
</div>


</body>
</html>

upload.php

<?php


if(isset($_POST["submit"])) {
    if(is_array($_FILES)) {


        $file = $_FILES['image']['tmp_name']; 
        $sourceProperties = getimagesize($file);
        $fileNewName = time();
        $folderPath = "upload/";
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $imageType = $sourceProperties[2];


        switch ($imageType) {


            case IMAGETYPE_PNG:
                $imageResourceId = imagecreatefrompng($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagepng($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
                break;


            case IMAGETYPE_GIF:
                $imageResourceId = imagecreatefromgif($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagegif($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
                break;


            case IMAGETYPE_JPEG:
                $imageResourceId = imagecreatefromjpeg($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagejpeg($targetLayer,$folderPath. $fileNewName. "_thump.". $ext);
                break;


            default:
                echo "Invalid Image type.";
                exit;
                break;
        }


        move_uploaded_file($file, $folderPath. $fileNewName. ".". $ext);
        echo "Image Resize Successfully.";
    }
}


function imageResize($imageResourceId,$width,$height) {


    $targetWidth =200;
    $targetHeight =200;


    $targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
    imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);


    return $targetLayer;
}
?>
0
Abd Abughazaleh

Vous pouvez également utiliser la bibliothèque Imagine. Il utilise D.ieu et Imagick.

0
ziiweb