La communauté ALL HTML c'est 58233 membres à ce jour dont 1 inscrits aujourd'hui et 34 depuis une semaine.
Cet article est actuellement publié sur le site.
Article publié le mercredi 25 juillet 2007 par elizabeth.
Cet article est classé dans les catégories « PHP »
Ce tutoriel vous aide à uploader une image .jpg qui sera redimentionnée proportionnellement, avant d'être copiée sur le serveur, puis génèrera une miniature proportionnelle de cette image, le tout enregistré dans une base de données. Ce code est améliorable, j'aimerais pouvoir gérer les gifs aussi, avis aux pros....
Petite fée.
<?php require_once('../Connections/anpot.php'); ?>
<?php
//
//************************ pour l'upload ***********************
// à enlever chez free : set_time_limit(0);
// pour autoriser la taille d'upload au niveau du php.ini
ini_set("post_max_size","52428800");
ini_set("memory_limit","52428800");
ini_set("upload_max_filesize","52428800"); //valeur en octets
// Repertoire de stockage de la grande image, chemin par rapport au fichier d'upload (celui-ci)
$dossier_grd = "../sources/images/grd";
// Repertoire de stockage de la petite image, chemin par rapport au fichier d'upload (celui-ci)
$dossier_ptt = "../sources/images/ptt";
// Poids max autorisé par le serveur
$MaxSize = 52428800;
// Largeur max de l'image en pixels autorisé à l'upload
$Maxwidth = 2048;
// Hauteur max de l'image en pixels autorisé à l'upload
$Maxheight = 2048;
// Type de fichier autorisé : seulement les jpg (si vous savez autoriser les gifs ça m'intéresse)
$ValidType = array("image/pjpeg"=>"jpg","image/jpeg"=>"jpg");
// nouveau nom de la grande image, ici en fonction du timestamp pour qu'il soit tjrs unique.
$NomImage = time();
//*********************** fin pour l'upload ********************
$up1 = false;
$up2 = false;
$upload = false;
//**************************************************************
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
//************************************************************** photo *************
if (!empty($_POST['fichier'])) {
$up1 = false;
$up2 = false;
// ******************* pour la grande photo ********
// Contrôle des messages d'erreur
if(!isset($_FILES['fichier'])) exit("Fichier absent <br><br><a href='javascript:history.back()'>[Charger une nouvelle image]</a>");
if($_FILES['fichier']['size'] > $MaxSize) exit("Image trop lourde <br><br><a href='javascript:history.back()'>[Charger une nouvelle image]</a>");
$infos_img = getimagesize($_FILES['fichier']['tmp_name']);
if(($infos_img[0] >= $Maxwidth) & ($infos_img[1] >= $Maxheight)) exit("Vous avez dépassé la dimension maximum autorisée qui est de $Maxwidth*$Maxheight pixels <br><br><a href='javascript:history.back()'>[Charger une nouvelle image]</a>");
$ext = "";
if(array_key_exists($_FILES['fichier']['type'],$ValidType)) $ext = $ValidType[$_FILES['fichier']['type']];
if(empty($ext)) exit("Type de fichier invalide <br><br><a href='javascript:history.back()'>[Charger une nouvelle image]</a>");
// Vérification de l'upload
if(!move_uploaded_file($_FILES['fichier']['tmp_name'], $dossier_grd."/".$NomImage.".".$ext))
{
exit("l'upload a échoué <br><br><a href='javascript:history.back()'>[Charger une nouvelle image]</a>");
}else{
// Création de la grande photo ***************************************************************
$image_mini=$dossier_grd."/".$NomImage.".".$ext;
$fichierSource = $image_mini;
}
// Définition du format de l'image
if ($infos_img[0] > $infos_img[1] ) {
// si la largeur est plus grande que la hauteur : Format paysage
$largeurDestination = 440;
$hauteurDestination = 440 * ($infos_img[1] / $infos_img[0]) ;
}elseif ($infos_img[1] > $infos_img[0] ) { // si la hauteur est plus grande que la Largeur : Format portrait
$hauteurDestination = 440;
$largeurDestination = 440 * ($infos_img[0] / $infos_img[1]) ;
}else if ($infos_img[1] == $infos_img[0] ) { // si la largeur est égale à la hauteur : Format carré
$largeurDestination = 440 ;
$hauteurDestination = 440;
}
//Crée l'image vide avec les dimensions
$im = ImageCreateTrueColor ($largeurDestination, $hauteurDestination)
or die ("Erreur lors de la création de l'image miniature");
//Prends l'image d'origine
$source = ImageCreateFromJpeg($fichierSource);
//Redimensionnement de L'image
$largeurSource = imagesx($source);
$hauteurSource = imagesy($source);
//Création, enregistrement de l'image redimentionnée
ImageCopyResampled($im, $source, 0, 0, 0, 0, $largeurDestination, $hauteurDestination, $largeurSource, $hauteurSource);
$miniature = $fichierSource;
ImageJpeg ($im, $miniature);
?>
<?php
$PhotoGrd=$NomImage.".".$ext;
$up1=true;
//**********************Génération de la petite vignette*******************************************
if($up1 == true){
// copie dans repertoire pour les petites photos, et renomme la vignette en ajoutant ptt devant le nom de la grande :
$NomImage = 'ptt'.$PhotoGrd;
if (copy($dossier_grd."/".$PhotoGrd,$dossier_ptt."/".$NomImage))
{
// Création d'une miniature
$image_mini=$dossier_ptt."/".$NomImage;
$fichierSource = $image_mini;
}
// Définition du format de l'image
if ($infos_img[0] > $infos_img[1] ) { // si la largeur est plus grande que la hauteur : Format paysage
$largeurDestination = 85;
$hauteurDestination = 85 * ($infos_img[1] / $infos_img[0]) ;
}elseif ($infos_img[1] > $infos_img[0] ) { // si la hauteur est plus grande que la Largeur : Format portrait
$hauteurDestination = 85;
$largeurDestination = 85 * ($infos_img[0] / $infos_img[1]) ;
}else if ($infos_img[1] == $infos_img[0] ) { // si la largeur est égale à la hauteur : Format carré
$largeurDestination = 85 ;
$hauteurDestination = 85;
}
//Crée l'image vide avec les dimensions
$im = ImageCreateTrueColor ($largeurDestination, $hauteurDestination)
or die ("Erreur lors de la création de l'image miniature");
//Prends l'image d'origine
$source = ImageCreateFromJpeg($fichierSource);
//Redimensionnement de L'image
$largeurSource = imagesx($source);
$hauteurSource = imagesy($source);
//Création, enregistrement de l'image miniature
ImageCopyResampled($im, $source, 0, 0, 0, 0, $largeurDestination, $hauteurDestination, $largeurSource, $hauteurSource);
$miniature = $fichierSource;
ImageJpeg ($im, $miniature);
?>
<?php
$PhotoPtt=$NomImage;
$up2=true;
} else {
echo "La copie du fichier $NomImage n'a pas réussi...\n";
}
}
// ********* enregistrement dans la base de donnée
if ($up1 == true AND $up2 == true) {
$upload = true;
}
if ($upload) {
$_POST['photoptt'] = $PhotoPtt;
$_POST['photogrd'] = $PhotoGrd;
$insertSQL = sprintf("INSERT INTO image (id, photoptt, photogrd) VALUES (%s, %s, %s)",
GetSQLValueString($_POST['id'], "int"),
GetSQLValueString($_POST['photoptt'], "text"),
GetSQLValueString($_POST['photogrd'], "text"));
mysql_select_db($database_anpot, $anpot);
$Result1 = mysql_query($insertSQL, $anpot) or die(mysql_error());
$insertGoTo = "ajout-confirm.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
//***************************
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>upload</title>
<link href="../../styles.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.Style2 {color: #000000}
.Style3 {
font-family: Georgia, "Times New Roman", Times, serif;
color: #666666;
font-weight: bold;
font-size: 18px;
}
.Style10 { font-family: Georgia, "Times New Roman", Times, serif;
color: #666666;
}
.titre {font-weight: bold}
.Style14 {font-family: Georgia, "Times New Roman", Times, serif; color: #666666; font-weight: bold; font-size: 24px; }
.Style17 {color: #990000; font-weight: bold; }
-->
</style>
</head>
<body>
<span class="titre"><span class="Style10"><em>espace administrateur </em></span></span>
<div align="center"><span class="sous-titre titre Style2"><br />
<span class="Style3">Ajout d'une photo </span> </span></div>
<table width="729" height="441" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="form1">
<table align="center">
<tr valign="baseline">
<td colspan="2" align="right" nowrap>: : </td>
</tr>
<tr valign="top">
<td width="306" align="right" nowrap><strong>Photo</strong> (maxi 2048 pixels de long <span class="Style17">ou</span> de large) :</td>
<td width="357"><input name="fichier" type="file" class="fields" size="25"></tr>
<tr valign="top">
<td colspan="2" align="center" nowrap><br />
<p> </p> <p>
<input type="submit" value="Insérer l'enregistrement">
</p></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form1">
</form>
<p> </p></td>
</tr>
</table>
</body>
</html>