IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

Combiner une classe Upload et une classe ImageResize


Sujet :

Langage PHP

  1. #1
    Membre éclairé
    Homme Profil pro
    Ingénieur en électrotechnique retraité
    Inscrit en
    Décembre 2008
    Messages
    1 577
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 72
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur en électrotechnique retraité

    Informations forums :
    Inscription : Décembre 2008
    Messages : 1 577
    Points : 803
    Points
    803
    Par défaut Combiner une classe Upload et une classe ImageResize
    Bonjour à toutes et tous,

    J'ai créé deux classes adaptées de codes existants.
    La première classe Upload fonctionne bien en autonome.
    Je voudrais que la valeur de retour de la méthode ImageResize::save() puisse être utilisée avant enregistrement par la classe Upload mais je ne sais pas quelle valeur de retour envoyer pour l'ntégrer dans la classe Upload avant de l'enregistrer avec move_uploaded_file.

    Classe Upload:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    <?php
     
    /**
     * class Upload
     * Version 1.0.0 (30/06/22)
     * Author moimp
     * Based on https://github.com/grunk/Pry/blob/fa3104194aeec40c416e53f742f1ad4575561f13/Pry/File/Upload.php#L206
     * Documentation on https://github.com/grunk/Pry/tree/master/doc
    
    namespace Upload;
    
    require_once('FileTools.php');
    require_once('StringTools.php');
    
    use FileTools\FileTools;
    use StringTools\StringTools;
    
    
    /**
     * Class to upload multiple files.
     * Optional use of finfo or mimemagic (see https://rubygems.org/gems/mimemagic?locale=fr)
     */
     
    class Upload
    {
     
    	const MIME_CHECK_BROWSER	= 1;
    	const MIME_CHECK_FINFO		= 2;
    	const MIME_CHECK_MIMETYPE	= 3;
    	const MIME_CHECK_NONE		= 4;
    	const REQUIRE_ALL			= 1;
    	const REQUIRE_YES			= 2;
    	const REQUIRE_NO			= 3;
    	const WMODE_OVERWRITE		= 1;
    	const WMODE_COPY			= 2;
    	const WMODE_CANCEL			= 3;
    /*
    
    	/**
    	 * Max filesize in bytes
    	 * @var int
    	 */
    	private $maxFileSize;
     
    	/**
    	 * Targetpath for uploaded files
    	 * @var string
    	 */
    	private $uploadDir;
     
    	/**
    	 * Path to magicmime file
    	 * @var string
    	 */
    	private $magicFile;
     
    	/**
    	 * Mime: check type
    	 * @var int
    	 */
    	private $mimetypeCheck;
     
    	/**
    	 * Writemode for uploading files
    	 * @var int
    	 */
    	private $writeMode;
     
    	/**
    	 * Secure mode or not
    	 * @var boolean
    	 */
    	private $secureMode;
     
    	/**
    	 * File required or not
    	 * @var int
    	 */
    	private $required;
     
    	/**
    	 * Allowed extensions
    	 * @var array
    	 */
    	private $extensions;
     
    	/**
    	 * Allowed mimetypes
    	 * @var array
    	 */
    	private $mimeTypes;
     
    	/**
    	 * Fieldnames for files to upload
    	 * @var string
    	 */
    	private $fieldName;
     
    	/**
    	 * Filename
    	 * @var string
    	 */
    	private $fileName;
     
    	/**
    	 * Filename cleaned or not
    	 * @var boolean
    	 */
    	private $cleanName;
     
    	/**
    	 * Préfix for filename
    	 * @var string
    	 */
    	private $prefix;
     
    	/**
    	 * Suffix for filename
    	 * @var <string
    	 */
    	private $suffix;
     
    	/**
    	 * Uploaded files summaries
    	 * @var array
    	 */
    	private $uploadedFileSummaries;
     
    	/**
    	 * Found errors
    	 * @var mixed
    	 */
    	private $errors;
     
    	/** Temporary name
    	 * @var string
    	 */
    	private $fileNameTmp;
     
     
    	private $_taille	= 0;
    	private $_nom		= '';
    	private $_temp		= '';
    	private $_mime		= '';
    	private $_image		= false;
    	private $_error		= '';
    	private $_ext		= '';
     
    	/**
    	 * Constructor
    	 * @param string $dir Target path for files
    	 * @param string $fieldName Uploading fieldnames
    	 * @param int [$mimetypeCheck] Mode to check type (browser)
    	 */
    	public function __construct(string $dir, string $fieldName, int $mimetypeCheck = 1)
    	{
    		$this->maxFileSize  = str_replace('M', '', ini_get('upload_max_filesize')) * 1024 * 1024;
    		$this->uploadDir	= $this->checkPath($dir);
    		$this->magicFile	= '';
    		$this->mimetypeCheck= intval($mimetypeCheck);
    		$this->writeMode	= self::WMODE_OVERWRITE;
    		$this->required		= self::REQUIRE_NO;
    		$this->extensions	= array('jpg', 'png', 'gif');
    		$this->mimeTypes	= array('image/gif', 'image/jpeg', 'image/png', 'text/plain', 'application/pdf');
    		$this->fieldName	= $fieldName;
    		$this->fileName		= '';
    		$this->fileNameTmp	= '';
    		$this->prefix		= '';
    		$this->suffix		= '';
    		$this->uploadedFileSummaries= array();
    		$this->secureMode	= false;
    		$this->cleanName	= false;
    		$this->errors		= array();
    	}
     
    	/**
    	 * Trigger fileuploads
    	 * @return array
    	 */
    	public function upload()
    	{
    		if (!isset($_FILES[$this->fieldName]['tmp_name']))
    			throw new \UnexpectedValueException('Error: No filedata');
     
    		$nbFile = count($_FILES[$this->fieldName]['tmp_name']);
     
    		for ($i = 0; $i < $nbFile; $i++) {
    			$this->fileNameTmp = '';
    			$this->_taille	= $_FILES[$this->fieldName]['size'][$i];
    			$this->_nom		= $_FILES[$this->fieldName]['name'][$i];
    			$this->_temp	= $_FILES[$this->fieldName]['tmp_name'][$i];
    			$this->_mime	= $_FILES[$this->fieldName]['type'][$i];
    			$this->_image	= false;		// added by moimp
    			if (!empty($this->_nom))
    				$this->_ext	= FileTools::getExtension($this->_nom);
    			$this->_error	= $_FILES[$this->fieldName]['error'][$i];
     
    			if ($this->_error == UPLOAD_ERR_OK and is_uploaded_file($_FILES[$this->fieldName]['tmp_name'][$i]))
    			{
    				if ($this->mimetypeCheck == self::MIME_CHECK_FINFO)
    				{
    					$finfo			= new \finfo(FILEINFO_MIME, $this->magicFile);
    					$this->_mime	= $finfo->file(realpath($this->_temp));
    					// Can return mimetypes as "text/plain; charset=utf-8"
    					$posSemiCol  = strpos($this->_mime, ';');
    					if ($posSemiCol !== false)
    						$this->_mime = substr($this->_mime, 0, $posSemiCol);
    				}
    				elseif ($this->mimetypeCheck == self::MIME_CHECK_MIMETYPE)
    					$this->_mime = mime_content_type(realpath($this->_temp));
    				elseif ($this->mimetypeCheck == self::MIME_CHECK_NONE)
    					$this->_mime = false;
     
    				if ($this->checkSize())
    				{
    					if ($this->checkExtension())
    					{
    						if ($this->checkMime())
    						{
    							// following code added by moimp
    							$this->getImgData();
    							if ($this->_image === 'err')
    							{
    								$this->errors[$i] = "The uploaded file is not an image.";
    							}
    							// end of added code
    							$this->buildName();
    							if ( ! $this->write() )
    							{
    								$this->errors[$i] = "Cannot write on harddisk. ";
    							}
    						}
    						else
    						{
    							$this->errors[$i] = "This filetype is not allowed. ";
    						}
    					}
    					else
    					{
    						$this->errors[$i] = "This file extension is not allowed. ";
    					}
    				}
    				else
    				{
    					$this->errors[$i] = "Filesize exceeds the allowed size. ";
    				}
    			}
    			else
    			{
    				if ($this->required == self::REQUIRE_ALL or $this->required == self::REQUIRE_YES and $i == 0)
    					$this->errors[$i] = "Error by uploading. Too big filesize or no required file? ";
    			}
    		}
     
    		return $this->getError();
    	}
     
    	/**
    	 * Define max filesize.
    	 * Allows (int) or string as 500K, 2M
    	 * @param mixed $size
    	 * @return Upload
    	 */
    	public function setMaxFileSize(string $size)
    	{
    		$this->maxFileSize = FileTools::getByteSize($size);
    		return $this;
    	}
     
    	/**
    	 * Define path for magicmime files
    	 * @param string $dir
    	 * @return Upload
    	 */
    	/*
    	public function setMagicFile($path)
    	{
    		$this->magicFile = $path;
    		return $this;
    	}
    	*/
     
    	/**
    	 * Define writemode
    	 * @param int $mode (one of constants WMODE_OVERWRITE, WMODE_COPY, WMODE_CANCEL)
    	 * @return Upload
    	 */
    	public function setWriteMode($mode)
    	{
    		$this->writeMode = intval($mode);
    		return $this;
    	}
     
    	/**
    	 * Define if files are required or not
    	 * @param int $mode
    	 * @return Upload
    	 */
    	public function setRequired($mode)
    	{
    		$this->required = intval($mode);
    		return $this;
    	}
     
    	/**
    	 * Define a (string) or multiple (array) of allowed extensions
    	 * @param mixed $newExt
    	 * @return Upload
    	 */
    	public function setAllowedExtensions($newExt)
    	{
    		if (is_array($newExt))
    			foreach ($newExt as $value)
    				$this->extensions[] = $value;
    		else
    			$this->extensions[] = $newExt;
     
    		return $this;
    	}
     
    	/**
    	 * Return allowed extensions
    	 * @return array
    	 */
    	public function getExtensions()
    	{
    		return $this->extensions;
    	}
     
    	/**
    	 * Remove an extension
    	 * @param string $extToRemove
    	 * @return Upload
    	 */
    	public function removeExtension(string $extToRemove)
    	{
    		$key = array_search($extToRemove, $this->extensions);
    		if ($key)
    			unset($this->extensions[$key]);
     
    		return $this;
    	}
     
    	/**
    	 * Remove all extensions
    	 * @return Upload
    	 */
    	public function flushAllowedExtensions()
    	{
    		$this->extensions = array();
    		return $this;
    	}
     
    	/**
    	 * Define a (string) or multiple (array) of allowed mimetypes
    	 * @param mixed $newMime
    	 * @return Upload
    	 */
    	public function setAllowedMime($newMime)
    	{
    		if (is_array($newMime))
    			foreach ($newMime as $value)
    				$this->mimeTypes[] = $value;
    		else
    			$this->mimeTypes[] = $newMime;
     
    		return $this;
    	}
     
    	/**
    	 * Return allowed mimetypes
    	 * @return array
    	 */
    	public function getMime()
    	{
    		return $this->mimeTypes;
    	}
     
    	/**
    	 * Remove a mimetype
    	 * @param string $mimeToRemove
    	 * @return Upload
    	 */
    	public function removeMime(string $mimeToRemove)
    	{
    		$key = array_search($mimeToRemove, $this->mimeTypes);
    		if ($key)
    			unset($this->mimeTypes[$key]);
     
    		return $this;
    	}
     
    	/**
    	 * Remove all mimetypes
    	 * @return Upload
    	 */
    	public function flushAllowedMime()
    	{
    		$this->mimeTypes = array();
    		return $this;
    	}
     
    	/**
    	 * Define filename after uploaded
    	 * @param string $name
    	 * @return Upload
    	 */
    	public function setFileName(string $name)
    	{
    		$this->fileName = trim($name);
    		return $this;
    	}
     
    	/**
    	 * Define préfix of filename
    	 * @param string $prefix
    	 * @return Upload
    	 */
    	public function setPrefix(string $prefix)
    	{
    		$this->prefix = trim($prefix);
    		return $this;
    	}
     
    	/**
    	 * Define suffix of filename
    	 * @param string $suffix
    	 * @return Upload
    	 * Note: impact basename
    	 */
    	public function setSuffix(string $suffix)
    	{
    		$this->suffix = trim($suffix);
    		return $this;
    	}
     
    	/**
    	 * Define securemode where application files or dangerous files are not allowed
    	 * @param boolean $mode
    	 * @return Upload
    	 */
    	public function setSecureMode(bool $mode)
    	{
    		$this->secureMode = $mode;
    		return $this;
    	}
     
    	/**
    	 * Enable or disabled cleaning of filename 
    	 * @param boolean $bool
    	 * @return Upload
    	 */
    	public function cleanName(bool $bool)
    	{
    		$this->cleanName = $bool;
    		return $this;
    	}
     
    	/**
    	 * Return an array of all errors
    	 * @return mixed
    	 */
    	public function getError()
    	{
    		if (!empty($this->errors))
    			return $this->errors;
    		else
    			return false;
    	}
     
    	/**
    	 * Return an array of all sent files
    	 * @return array
    	 */
    	public function getSummaries()
    	{
    		return $this->uploadedFileSummaries;
    	}
     
    	/**
    	 * Get imagedata
    	 * @return wether imagedata or boolean if uploaded file is not an image
    	 * Function added by moimp
    	 */
    	private function getImgData()
    	{
    		if (strpos($this->_mime, 'image/') !== false)
    		{
    			$this->_image = getimagesize(realpath($this->_temp));
    			if ( !(
    				is_int($this->_image[0]) && 
    				is_int($this->_image[1]) && 
    				is_int($this->_image[2]) && 
    				is_int($this->_image['bits']) &&
    				strpos($this->_image['mime'], 'image/') !== false
    				)
    				)
    			{
    				$this->_image = 'err';
    			}
    		}
    		else
    		{
    			$this->_image = false;
    		}
     
    	}
     
    	/**
    	 * Check if a path is correct
    	 * @param string $path
    	 * @return boolean
    	 */
    	private function checkPath(string $path)
    	{
    		$path = trim($path);
    		$path = rtrim($path, '/\\').'/'; // line added by moimp to allowed pathes ended wether with or whithout '/' or '\'
     
    		if (!is_dir($path))
    			throw new \InvalidArgumentException($path . ' is not a valid path');
    		if (!is_writable($path))
    			throw new \RuntimeException($path . ' is not open in write mode');
     
    		return $path;
    	}
     
    	/**
    	 * Write file on harddisk on the wished place
    	 * @return boolean
    	 */
    	private function write()
    	{
     
    		if ($this->writeMode == self::WMODE_OVERWRITE)
    		{
    			if ($this->exist())
    				unlink($this->uploadDir . $this->fileNameTmp);
    			$uploaded = move_uploaded_file($this->_temp, $this->uploadDir . $this->fileNameTmp);
    		}
    		elseif ($this->writeMode == self::WMODE_COPY)
    		{
    			if ($this->exist())
    				$this->fileName = 'Copy_' . $this->fileNameTmp;
    			$uploaded = move_uploaded_file($this->_temp, $this->uploadDir . $this->fileNameTmp);
    		}
    		else
    		{
    			if (!$this->exist())
    				$uploaded = move_uploaded_file($this->_temp, $this->uploadDir . $this->fileNameTmp);
    			else
    				$uploaded = false;
    		}
     
    		if ($uploaded)
    		{
    			$this->uploadedFileSummaries[] = array(
    				'nom'	=> $this->fileNameTmp,
    				'nom_base' => $this->_nom,
    				'ext'	=> $this->_ext,
    				'mime'	=> $this->_mime,
    				'path'	=> $this->uploadDir,
    				'octet'	=> $this->_taille,
    				'size'	=> number_format($this->_taille / 1024, 2, '.', ''),
    				'image'	=> $this->_image		// added by moimp
    			);
    			return true;
    		}
    		return false;
    	}
     
    	/**
    	 * Check filesize
    	 * @return boolean
    	 */
    	private function checkSize()
    	{
    		if ($this->maxFileSize > $this->_taille)
    			return true;
    		return false;
    	}
     
    	/**
    	 * Check the filename extension
    	 * @return boolean
    	 */
    	private function checkExtension()
    	{
    		if (in_array($this->_ext, $this->extensions))
    			return true;
    		return false;
    	}
     
    	/**
    	 * Check mimetype of the file
    	 * @return boolean
    	 */
    	private function checkMime()
    	{
    		if ($this->mimetypeCheck != self::MIME_CHECK_NONE)
    		{
    			if ($this->secureMode) {
    				if (!in_array($this->_mime, $this->mimeTypes) || strpos($this->_mime, 'application') || preg_match("/.php$|.php3$|.php5$|.inc$|.js$|.exe$/i", $this->_ext))
    					return false;
    			} else {
    				if (!in_array($this->_mime, $this->mimeTypes))
    					return false;
    			}
    		}
    		return true;
    	}
     
    	/**
    	 * Build filename
    	 * @return void
    	 */
    	private function buildName()
    	{
    		if ($this->fileName == '')
    			$this->fileNameTmp = substr($this->_nom, 0, strrpos($this->_nom, '.'));
    		else
    			$this->fileNameTmp = $this->fileName;
     
    		if ($this->cleanName)
    			$this->fileNameTmp = StringTools::clean($this->fileNameTmp);
    		$this->fileNameTmp = $this->prefix . $this->fileNameTmp . $this->suffix . '.' . $this->_ext;
    	}
     
    	/**
    	 * Check if file exists
    	 * @access private
    	 * @return boolean
    	 */
    	private function exist()
    	{
    		if (file_exists($this->uploadDir . $this->fileNameTmp))
    			return true;
    		return false;
    	}
    }
    Classe ImageResize:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    <?php
     
    /**
     * Class ImageResize to handle images
     * Version 1.0.0 (10/07/22)
     * Author moimp
     * Based on https://waytolearnx.com/2019/07/redimensionner-une-image-en-php.html
     */
     
    namespace ImageResize;
     
    class ImageResize
    {
     
    	/**
    	 * Sourcepath
    	 * @var string
    	 */
    	private $sourcePath;
     
    	/**
    	 * Targetpath
    	 * @var string
    	 */
    	private $targetPath;
     
    	/**
    	 * Save proportion or not
    	 * @var boolean
    	 */
    	private $proportion;
     
    	/**
    	 * Basename of imagename
    	 * @var boolean
    	 */
    	private $imagename;
     
    	/**
    	 * Infos of image
    	 * @var array
    	 */
    	private $infos;
     
    	/**
    	 * Imagewidth
    	 * @var int
    	 */
    	private $sourceWidth;
     
    	/**
    	 * Imageheight
    	 * @var int
    	 */
    	private $sourceHeight;
     
    	/**
    	 * fixTargetWidth
    	 * @var int
    	 */
    	private $fixTargetWidth;
     
    	/**
    	 * maxTargetHeight
    	 * @var int
    	 */
    	private $fixTargetHeight;
     
    	/**
    	 * targetWidth
    	 * @var int
    	 */
    	private $targetWidth;
     
    	/**
    	 * targetHeight
    	 * @var int
    	 */
    	private $targetHeight;
     
    	/**
    	 * Mimetype
    	 * @var string
    	 */
    	private $mime;
     
     
    	/**
    	 * Constructor
    	 * @param string $sourcePath file to be resized
    	 * @param boolean $proportion proprtion is to be saved or not
    	 */
    	public function __construct(string $sourcePath, string $targetPath, bool $proportion = true)
    	{
    		$this->sourcePath		= $sourcePath;
    		$this->targetPath		= $targetPath;
    		$this->proportion		= $proportion;
    		$this->imagename		= basename($sourcePath);
    		$this->infos			= getimagesize($sourcePath);
    		list($this->sourceWidth, $this->sourceHeight) = $this->infos;
    		$this->mime				= $this->infos['mime'];
    		$this->fixTargetWidth	= null;
    		$this->fixTargetHeight	= null;
    		$this->targetWidth		= $this->sourceWidth;
    		$this->targetHeight		= $this->sourceHeight;
    	}
     
    	/**
    	 * Save image
    	 */
    	public function save(){
     
    		// Set target size
    		if ($this->proportion)
    		{
    			$rate = $this->sourceWidth / $this->sourceHeight;
    			if (isset($this->fixTargetWidth) && !isset($this->fixTargetHeight))
    			{
    				$this->targetWidth	= $this->fixTargetWidth;
    				$this->targetHeight	= $this->targetWidth / $rate;
    			}
    			elseif (!isset($this->fixTargetWidth) && isset($this->fixTargetHeight))
    			{
    				$this->targetHeight	= $this->fixTargetHeight;
    				$this->targetWidth	= $this->targetHeight * $rate;
    			}
    			elseif (isset($this->fixTargetWidth, $this->fixTargetHeight))
    			{
    				throw new \Exception('You cannot set fixTargetWidth AND fixTargetHeight.');
    			}
    		}
    		else
    		{
    			if (isset($this->fixTargetWidth))
    				$this->targetWidth = $this->fixTargetWidth;
    			if (isset($this->fixTargetHeight))
    				$this->targetHeight	= $this->fixTargetHeight;
    		}
     
    		// Handle saving
    		$objImg	= imagecreatetruecolor($this->targetWidth, $this->fixTargetHeight);
    		$image	= $imageCreateFunc($this->targetPath);
    		imagecopyresampled($objImg, $image, 0, 0, 0, 0, $this->targetWidth, $this->targetHeight, $this->sourceWidth, $this->sourceHeight);
    		$imageSaveFunc($objImg, $this->targetPath);
     
     
     
    		// ...
    	}
     
    	private function setFunctions()
    	{
    		switch ($this->mime) {
    				case 'image/jpeg':
    						$imageCreateFunc	= 'imagecreatefromjpeg';
    						$imageSaveFunc		= 'imagejpeg';
    						break;
     
    				case 'image/png':
    						$imageCreateFunc	= 'imagecreatefrompng';
    						$imageSaveFunc		= 'imagepng';
    						break;
     
    				case 'image/gif':
    						$imageCreateFunc	= 'imagecreatefromgif';
    						$imageSaveFunc		= 'imagegif';
    						break;
     
    				default: 
    						throw new Exception('Unknown image type');
    		}
     
    	}
     
    	public function setFixTargetWidth(int $width)
    	{
    		$this->fixTargetWidth = $width;
    		return $this;
    	}
     
    	public function setFixTargetHeight(int $height)
    	{
    		$this->fixTargetHeight = $height;
    		return $this;
    	}
     
    }
    Code de test:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    <?php declare(strict_types=1); ?>
     
    <!DOCTYPE html>
     
    <body>
    	<form method="post" enctype='multipart/form-data'>
    		<!-- <input type="hidden" name="MAX_FILE_SIZE" value="100000"> -->
    		<input type="file" name="files[]"><br>
    		<input type="file" name="files[]"><br>
    		<input type="submit" name="submit" value="Enregistrer"><br>
    	</form>
    	<script>
    		if (! document.querySelector("[type='file']").form.hasAttribute('enctype'))
    			alert("You have a field with type 'file' without parentform has an attribute \"enctype='multipart/form-data'\".");
    	</script>
    </body>
     
    <?php
     
    require_once("../classes/moimp/Upload.php");
    require_once("../classes/moimp/ImageResize.php");
     
    use Upload\Upload;
    use ImageResize\ImageResize;
     
    $post = $_POST;
     
    if (isset($post['submit']))
    {
    	$up = new Upload(__dir__, 'files', Upload::MIME_CHECK_FINFO);
    	$img= new ImageResize($_FILES['files']['tmp_name'][0], __dir__, true);
     
    	// Remove all extensions
    	//$up->flushAllowedExtensions();
     
    	// Define a (string) or multiple (array) of allowed extensions
    	//$up->setAllowedExtensions(['type1']);
     
    	// Remove an extension
    	//removeExtension($extToRemove);
     
    	// Define a (string) or multiple (array) of allowed mimetypes
    	//$up->setAllowedMime($mime);
     
    	// Remove one mimetype
    	//removeMime($mimeToRemove);
     
    	// Remove all mimetypes
    	//flushAllowedMime();
     
    	//$img->setFixTargetWidth(50);
    	$img->setFixTargetHeight(100);
    	$img->save();
    	var_dump($img);
     
    	$up->setMaxFileSize('5M')->setWriteMode(Upload::WMODE_OVERWRITE);
    	$up->setRequired(Upload::REQUIRE_YES);
    	$up->setSecureMode(true);
    	$up->getError();
     
    	$errors = $up->upload();
    	var_dump($up);
    	if(empty($errors)){
    		$up->getSummaries();
    		var_dump($up->getSummaries() );
    	}
    	else{
    		foreach($errors as $key=>$err){
    			echo '<span style="color:red;font-weight:bold;">'.$err."</span>";
    		}
    	}
    }

  2. #2
    Membre actif
    Homme Profil pro
    Webmaster - Développeur/intégrateur web
    Inscrit en
    Septembre 2011
    Messages
    210
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Jura (Franche Comté)

    Informations professionnelles :
    Activité : Webmaster - Développeur/intégrateur web
    Secteur : Conseil

    Informations forums :
    Inscription : Septembre 2011
    Messages : 210
    Points : 246
    Points
    246
    Par défaut
    Bonjour,

    Je ne vois pas tellement l'intérêt d'appeler $img->save() avant $up->upload(), pour moi, il faudrait plutôt faire le contraire :
    - 1. uploader l'image dans un répertoire temporaire en utilisant la classe "Upload";
    - 2. redimensionner l'image en utilisant la classe "ImageResize";
    - 3. supprimer l'image temporaire;

    Où alors, j'ai pas compris...

    Il y a un quelque chose qui me semble bizarre au niveau de la méthode ImageResize->save(), les données de l'image source ne sont pas utilisées mis à part la largeur et la hauteur, est-ce qu'il ne manque pas une fonction du genre "imagecopymerge ?

    Sinon, c'est effectivement dans cette méthode que l'on pourrait appeler $up->upload(), personnellement, je trouve pas ça très logique mais bon...
    Si vous avez besoin d'une librairie permettant de gérer facilement les fichiers et les dossiers en PHP... ou si vous êtes juste curieux(se) :
    https://github.com/moDevsome/moFilesManager

    N'hésitez pas à me faire un retour

  3. #3
    Membre éclairé
    Homme Profil pro
    Ingénieur en électrotechnique retraité
    Inscrit en
    Décembre 2008
    Messages
    1 577
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 72
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur en électrotechnique retraité

    Informations forums :
    Inscription : Décembre 2008
    Messages : 1 577
    Points : 803
    Points
    803
    Par défaut
    Citation Envoyé par Soundboy39 Voir le message
    Je ne vois pas tellement l'intérêt d'appeler $img->save() avant $up->upload(), pour moi, il faudrait plutôt faire le contraire :
    - 1. uploader l'image dans un répertoire temporaire en utilisant la classe "Upload";
    - 2. redimensionner l'image en utilisant la classe "ImageResize";
    - 3. supprimer l'image temporaire;
    Merci pour cette remarque. C'est effectivement plus clair et de plus ça permet de ne traiter qu'une chose à la fois.

    Citation Envoyé par Soundboy39 Voir le message
    Il y a un quelque chose qui me semble bizarre au niveau de la méthode ImageResize->save(), les données de l'image source ne sont pas utilisées mis à part la largeur et la hauteur, est-ce qu'il ne manque pas une fonction du genre "imagecopymerge ?
    Par contre là, j'ai un peu plus de difficultés. Dans le code que j'ai pris comme exemple, il y a une fonction imagecopyresampled() et je ne vois pas trop la différence avec imagecopymerge(). Je dois dire que je débute complètement avec le traitement d'image.

    Voici le code de la méthode ImageResize::save() après correction:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    	public function save(){
     
    		// Set target size
    		if ($this->proportion)
    		{
    			$rate = $this->sourceWidth / $this->sourceHeight;
    			if (isset($this->fixTargetWidth) && !isset($this->fixTargetHeight))
    			{
    				$this->targetWidth	= $this->fixTargetWidth;
    				$this->targetHeight	= $this->targetWidth / $rate;
    			}
    			elseif (!isset($this->fixTargetWidth) && isset($this->fixTargetHeight))
    			{
    				$this->targetHeight	= $this->fixTargetHeight;
    				$this->targetWidth	= $this->targetHeight * $rate;
    			}
    			elseif (isset($this->fixTargetWidth, $this->fixTargetHeight))
    			{
    				throw new \Exception('You cannot set fixTargetWidth AND fixTargetHeight.');
    			}
    		}
    		else
    		{
    			if (isset($this->fixTargetWidth))
    				$this->targetWidth = $this->fixTargetWidth;
    			if (isset($this->fixTargetHeight))
    				$this->targetHeight	= $this->fixTargetHeight;
    		}
     
    		// Handle saving
    		$objImg	= imagecreatetruecolor($this->targetWidth, $this->targetHeight);
    		$imageCreateFunc	= $this->imageCreateFunc;
    		$imageSaveFunc		= $this->imageSaveFunc;
    		$image	= $imageCreateFunc($this->targetPath);
    		imagecopyresampled($objImg, $image, 0, 0, 0, 0, $this->targetWidth, $this->targetHeight, $this->sourceWidth, $this->sourceHeight);
    		$imageSaveFunc($objImg, $this->targetPath);
    	}
    A la première utilisation, ce code génère deux erreurs que je ne comprends pas:
    1ère erreur:
    imagecreatefrompng(C:\wamp64\www\proginet\appSirep\_test/0b.png): failed to open stream: No such file or directory in C:\wamp64\www\proginet\appSirep\classes\moimp\ImageResize.php on line 34
    2ème erreur:
    Warning: imagecopyresampled() expects parameter 2 to be resource, bool given in C:\wamp64\www\proginet\appSirep\classes\moimp\ImageResize.php on line 35
    EDIT: Je comprends cette erreur puisque à la suite de la ligne 34, $image vaut false.

    Une image noire est créée.

    Je n'ai plus ces erreurs si j'actualise la page mais l'image reste une image noire.

    EDIT 2: Précision qui peut avoir son importance: J'utilise PHP 7.4.0.

  4. #4
    Membre éclairé
    Homme Profil pro
    Ingénieur en électrotechnique retraité
    Inscrit en
    Décembre 2008
    Messages
    1 577
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 72
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur en électrotechnique retraité

    Informations forums :
    Inscription : Décembre 2008
    Messages : 1 577
    Points : 803
    Points
    803
    Par défaut
    C'est bon, j'ai trouvé un magnifique tuto qui m'a permis de mieux comprendre ce que je fais et m'a aider à résoudre les erreurs restantes.

  5. #5
    Expert éminent sénior

    Homme Profil pro
    Développeur Web
    Inscrit en
    Septembre 2010
    Messages
    5 380
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Septembre 2010
    Messages : 5 380
    Points : 10 410
    Points
    10 410
    Par défaut
    Alternativement tu peux aussi utiliser ce module d'upload. Il est livré prêt à l'emploi avec une vingtaine d'exemples fonctionnels dont l'utilisation du module de traitement d'images, avec optimisation, redimensionnement, de même que recadrage et création de filigrane wysiwyg. Toutes ces fonctions peuvent être utilisées conjointement. Concernant le redimensionnement qui t'intéresse ici, tu peux définir une largeur ou une hauteur maximum, mais aussi les deux en même temps et dans ce cas le premier maximum atteint définira la taille maximale. Le module d'upload gère aussi les erreurs fatales du serveur ce qui peut être utile pour le traitement sur les images en cas de dépassement de la mémoire allouée pour le script.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 9
    Dernier message: 29/04/2015, 11h18
  2. [Débutant] Combiner deux classes pour n'en faire qu'une
    Par Domi2 dans le forum Mise en page CSS
    Réponses: 3
    Dernier message: 12/04/2015, 17h10
  3. Réponses: 8
    Dernier message: 17/07/2013, 12h06
  4. Combiner une zone cliquable avec effet lightbox?
    Par Payo Manuel dans le forum Balisage (X)HTML et validation W3C
    Réponses: 4
    Dernier message: 17/03/2011, 22h13
  5. Combiner une translation et une rotation
    Par slim_java dans le forum 3D
    Réponses: 1
    Dernier message: 24/03/2009, 16h00

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo