upload si resize mai multe imagini in php

Discutii despre script-uri si coduri PHP-MySQL, precum si lucru cu XML in PHP.
Avatar utilizator
evident
Mesaje: 168

upload si resize mai multe imagini in php

Am urmatorul script pentru upload si resize imagini cu php:

Cod: Selectaţi tot

<?php
if(isset($_POST['submit'])){
    include"include/initialize.php";

    $targetDir = "upload_poze/";
    $allowTypes = array('jpg','png','jpeg','gif');
    $NewImageWidth 		= 500;
    $NewImageHeight 	= 300;
    $Quality 		= 80;
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            $fileName = basename($_FILES['files']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;
            $destFilePath = $targetDir . $fileName;
           
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)){
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
                    $insertValuesSQL .= "('".$fileName."', NOW()),";
                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].', ';
                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].', ';
            }
        }
        
        if(!empty($insertValuesSQL)){
            $insertValuesSQL = trim($insertValuesSQL,',');
            
             $mydb->setQuery("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
             $insert = $mydb->executeQuery();
            if($insert){
                $errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
                $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
                $statusMsg = "Poze incarcate cu succes.".$errorMsg;
            }else{
                $statusMsg = "S-a intamplat ceva in timpul uploadului.Contactati administratorul site-ului ";
            }
        }
    }else{
        $statusMsg = 'Alegeti o imagine.';
    }

    echo $statusMsg;
    resizeImage($targetFilePath,$destFilePath,$NewImageWidth,$NewImageHeight,$Quality);
}
function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
   	list($iWidth,$iHeight,$type)	= getimagesize($SrcImage);
    $ImageScale          	= min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
    $NewWidth              	= ceil($ImageScale*$iWidth);
    $NewHeight             	= ceil($ImageScale*$iHeight);
    $NewCanves             	= imagecreatetruecolor($NewWidth, $NewHeight);

	switch(strtolower(image_type_to_mime_type($type)))
	{
		case 'image/jpeg':
			$NewImage = imagecreatefromjpeg($SrcImage);
			break;
		case 'image/png':
			$NewImage = imagecreatefrompng($SrcImage);
			break;
		case 'image/gif':
			$NewImage = imagecreatefromgif($SrcImage);
			break;
		default:
			return false;
	}

	// Resize Image
    if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
    {
        // copy file
        if(imagejpeg($NewCanves,$DestImage,$Quality))
        {
            imagedestroy($NewCanves);
            return true;
        }
    }
}
?>
<form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple >
    <input type="submit" name="submit" value="UPLOAD">
</form>
Am un folder cu 5 imagini cu numele "site" si un folder "poze" in folderul "site" cu 3 imagini
cand selectez imagini pentru upload din folderul "site" este totul ok doar ca se redimensioneaza doar ultima imagine.De ce?
Cand selectez imagini pentru upload din folderul "poze" nu ruleaza nimic. Daca selectez sa incarc doar o imagine imi da eroarea:

Cod: Selectaţi tot

Warning: getimagesize(upload_poze/20190324_142648.jpg): failed to open stream: No such file or directory in
in linia 58

Cod: Selectaţi tot

list($iWidth,$iHeight,$type)	= getimagesize($SrcImage);
Cum as putea modifica scriptul ca sa pot face upload la imagini fara problemele astea?

MarPlo Mesaje: 4343
1. Ca sa redimensioneze toate imaginile, urmatorul cod ar trebui sa fie in cadrul foreach():

Cod: Selectaţi tot

resizeImage($targetFilePath,$destFilePath,$NewImageWidth,$NewImageHeight,$Quality);
2. Nu stiu de ce nu merge si cu poze incarcate din alt folder, asta cred ca nu tine de php. Verifica cu var_dump($_FILES); sa vezi ce date sunt primite de la browser.

3. Scriptul e facut pentru upload mai multe imagini, nu una.
Ca sa functioneze cu una, incearca-l asa (nu am testat):

Cod: Selectaţi tot

<?php
if(isset($_POST['submit'])){
  include"include/initialize.php";

  $targetDir = "upload_poze/";
  $allowTypes = array('jpg','png','jpeg','gif');
  $NewImageWidth 		= 500;
  $NewImageHeight 	= 300;
  $Quality 		= 80;
  $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType ='';

  foreach($_FILES['files']['name'] as $key=>$val){
    $fileName = basename($_FILES['files']['name'][$key]);
    $targetFilePath = $targetDir . $fileName;
    $destFilePath = $targetDir . $fileName;
   
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    if(in_array($fileType, $allowTypes)){
      if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
        $insertValuesSQL .= "('".$fileName."', NOW()),";
        resizeImage($targetFilePath,$destFilePath,$NewImageWidth,$NewImageHeight,$Quality);
      }
      else $errorUpload .= $_FILES['files']['name'][$key].', ';
    }
    else $errorUploadType .= $_FILES['files']['name'][$key].', ';
  }
        
  if(!empty($insertValuesSQL)){
    $insertValuesSQL = trim($insertValuesSQL,',');
    
     $mydb->setQuery("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
     $insert = $mydb->executeQuery();
    if($insert){
      $errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
      $errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
      $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
      $statusMsg = "Poze incarcate cu succes.".$errorMsg;
    }
    else $statusMsg = "S-a intamplat ceva in timpul uploadului.Contactati administratorul site-ului ";
  }

  echo $statusMsg;
}

function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality){
  list($iWidth,$iHeight,$type)	= getimagesize($SrcImage);
  $ImageScale          	= min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
  $NewWidth              	= ceil($ImageScale*$iWidth);
  $NewHeight             	= ceil($ImageScale*$iHeight);
  $NewCanves             	= imagecreatetruecolor($NewWidth, $NewHeight);

	switch(strtolower(image_type_to_mime_type($type))){
    case 'image/jpeg':
      $NewImage = imagecreatefromjpeg($SrcImage);
      break;
    case 'image/png':
      $NewImage = imagecreatefrompng($SrcImage);
      break;
    case 'image/gif':
      $NewImage = imagecreatefromgif($SrcImage);
      break;
    default:
      return false;
	}

	// Resize Image
  if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight)){
    // copy file
    if(imagejpeg($NewCanves,$DestImage,$Quality)){
      imagedestroy($NewCanves);
      return true;
    }
  }
}
?>
<form action="" method="post" enctype="multipart/form-data">
  Select Image Files to Upload:
  <input type="file" name="files[]" multiple >
  <input type="submit" name="submit" value="UPLOAD">
</form>

Subiecte similare