Création d'une miniature à partir d'une image téléchargée
Je souhaite créer une vignette à partir d'une image téléchargée par un utilisateur afin que l'image ne soit pas écrasée. Mais aimerait aussi une copie de l'image originale.. Je voudrais donc que l'image originale envoie l'image originale à mon serveur et crée également une version thumb et l'envoie à mon serveur afin que je puisse appeler chacun d'eux pour chaque utilisateur qui télécharge sa propre image.
Ma table Utilisateur a 2 tables
`user_pic` longblob NOT NULL,
`user_pic_small` longblob NOT NULL,
Je ne suis pas crash chaud avec le côté image du codage mais c'est ce que j'ai jusqu'à présent.
Imageupload.php
> <form id="myForm" action="include/media.profileimage.upload.php"
> method="POST" enctype="multipart/form-data" target="ifr1">
> <input type = "file" name = "image_data" class = "input_text" style="width:800px;" >
> <input type = "submit" name = "submit" class = "btn_login" value = "Upload">
> </form>
Médias.profileimage.télécharger.php
if(isset($_FILES['image_data'])){
if(is_uploaded_file($_FILES['image_data']['tmp_name'])) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['image_data']['tmp_name']));
// get the image info..
$size = getimagesize($_FILES['image_data']['tmp_name']);
// our sql query
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic='".$imgData."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$imgData')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
Apprécierait toute aide ou guidance. Merci
9 réponses
Mise à jour:
Si vous voulez profiter D'Imagick (s'il est installé sur votre serveur). Note: je n'ai pas utilisé la nature D'Imagick writeFile
parce que j'avais des problèmes avec elle sur mon serveur. Le contenu du fichier put fonctionne aussi bien.
<?php
/**
*
* Generate Thumbnail using Imagick class
*
* @param string $img
* @param string $width
* @param string $height
* @param int $quality
* @return boolean on true
* @throws Exception
* @throws ImagickException
*/
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = reset(explode('.', $img));
if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}
// example usage
try {
generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
J'ai utilisé ceci, exécutez simplement la fonction après avoir stocké l'image originale et utilisez cet emplacement pour créer la vignette. Le modifier à votre convenance...
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == IMAGETYPE_GIF) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == IMAGETYPE_JPEG) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == IMAGETYPE_PNG) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
La fonction ci-dessus crée des images avec une vignette uniforme taille. Si l'image n'a pas les mêmes dimensions que la taille de la vignette spécifiée (proportionnellement), elle a juste un espace noir en haut et en bas.
Je suppose que vous avez déjà compris celui-ci. Mais je vois que vous stockez les images en tant que "longblobs", ce qui me conduit à penser que vous stockez tout le contenu binaire de la photo.
J'espère que vous avez réalisé qu'il est beaucoup plus logique de simplement stocker les noms de fichiers dans votre base de données, puis d'utiliser ces informations pour extraire les photos d'un dossier "upload" ou similaire.
Astuce-ne pas enregistrer un chemin de fichier.. juste le nom du fichier .. ajoutez les informations de chemin dans votre code si nécessaire. De cette façon, vous avoir le plus de liberté sur la ligne. Si vous devez modifier la structure des dossiers, vous pouvez le faire dans votre code plutôt que de modifier les enregistrements DB.
Je sais que c'est une vieille question, mais je suis tombé sur le même problème et j'ai essayé d'utiliser la fonction donnée dans la réponse D'Alex.
Mais la qualité du résultat jpeg était trop faible. J'ai donc changé un peu la fonction pour devenir plus utilisable dans mon projet et changé le "ImageCopyResampled" en "imagecopyresampled" ( selon cette recommandation).
Si vous avez des questions sur la façon d'utiliser cette fonction, essayez de jeter un oeil à la version bien documentée ici.
function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
list($original_width, $original_height, $original_type) = getimagesize($filepath);
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($original_type === 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
} else if ($original_type === 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
} else if ($original_type === 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
} else {
return false;
}
$old_image = $imgcreatefrom($filepath);
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
// figuring out the color for the background
if(is_array($background) && count($background) === 3) {
list($red, $green, $blue) = $background;
$color = imagecolorallocate($new_image, $red, $green, $blue);
imagefill($new_image, 0, 0, $color);
// apply transparent background only if is a png image
} else if($background === 'transparent' && $original_type === 3) {
imagesavealpha($new_image, TRUE);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, $thumbpath);
return file_exists($thumbpath);
}
Vous Pouvez Utiliser La Méthode La Plus Simple
<?php
function make_thumb($src, $dest, $desired_width) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);
}
$src="1494684586337H.jpg";
$dest="new.jpg";
$desired_width="200";
make_thumb($src, $dest, $desired_width);
?>
Juste au cas où vous auriez besoin de créer un pouce avec une largeur maximale et une hauteur maximale ...
function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){
$arr_image_details = getimagesize($img);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$percent = 100;
if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width);
if(floor(($height * $percent)/100)>$MaxHe)
$percent = (($MaxHe * 100) / $height);
if($width > $height) {
$newWidth=$MaxWe;
$newHeight=round(($height*$percent)/100);
}else{
$newWidth=round(($width*$percent)/100);
$newHeight=$MaxHe;
}
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($img);
$new_image = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$imgt($new_image, $updir."".$id."_t.jpg");
return;
}
}
J'espère que ce code aide à créer des vignettes pour les formats JPG, PNG et GIF.
<?php
$file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */
$pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);/* Name of the Image File*/
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
/* Adding image name _thumb for thumbnail image */
$file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
break;
case 'image/gif':
$img = imagecreatefromgif($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/gif');
break;
default: die();
}
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
?>
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
Téléchargement D'Image avec vignette générer
Télécharger.php
<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
//folder path setup
$target_path = $target_folder;
$thumb_path = $thumb_folder;
//file name setup
$filename_err = explode(".",$_FILES[$field_name]['name']);
$filename_err_count = count($filename_err);
$file_ext = $filename_err[$filename_err_count-1];
if($file_name != '')
{
$fileName = $file_name.'.'.$file_ext;
}
else
{
$fileName = $_FILES[$field_name]['name'];
}
//upload image path
$upload_image = $target_path.basename($fileName);
//upload image
if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
{
//thumbnail creation
if($thumb == TRUE)
{
$thumbnail = $thumb_path.$fileName;
list($width,$height) = getimagesize($upload_image);
$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
switch($file_ext){
case 'jpg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'jpeg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'png':
$source = imagecreatefrompng($upload_image);
break;
case 'gif':
$source = imagecreatefromgif($upload_image);
break;
default:
$source = imagecreatefromjpeg($upload_image);
}
imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
switch($file_ext){
case 'jpg' || 'jpeg':
imagejpeg($thumb_create,$thumbnail,100);
break;
case 'png':
imagepng($thumb_create,$thumbnail,100);
break;
case 'gif':
imagegif($thumb_create,$thumbnail,100);
break;
default:
imagejpeg($thumb_create,$thumbnail,100);
}
}
return $fileName;
}
else
{
return false;
}
}
if(!empty($_FILES['image']['name'])){
$upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');
//full path of the thumbnail image
$thumb_src = 'uploads/thumbs/'.$upload_img;
//set success and error messages
$message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";
}else{
//if form is not submitted, below variable should be blank
$thumb_src = '';
$message = '';
}
?>
<html>
<head>Image upload and generate thumbnail</head>
<body>
<div class="messages"><?php echo $message; ?></div>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php if($thumb_src != ''){ ?>
<div class="gallery">
<ul>
<li><img src="<?php echo $thumb_src; ?>" alt=""></li>
</ul>
</div>
<?php } ?>
</body>
</html>
<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","4000");
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["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$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);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);
$filename = "images/1-". $_FILES['file']['name']=time();
$filename1 = "images/2-". $_FILES['file']['name']=time();
$filename2 = "images/3-". $_FILES['file']['name']=time();
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>picture demo</title>
<link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>
<style type="text/css">
.help
{
font-size:11px; color:#006600;
}
body {
color: #000000;
background-color:#999999 ;
background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
.msgdiv{
width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>
</head><body>
<div align="center" id="err">
<?php echo $change; ?> </div>
<div id="space"></div>
<div id="container" >
<div id="con">
<table width="502" cellpadding="0" cellspacing="0" id="main">
<tbody>
<tr>
<td width="500" height="238" valign="top" id="main_right">
<div id="posts">
<img src="<?php// echo $filename; ?>" /> <img src="<?php// echo $filename1; ?>" />
<form method="post" action="" enctype="multipart/form-data" name="form1">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><Td style="height:25px"> </Td></tr>
<tr>
<td width="150"><div align="right" class="titles">Picture
: </div></td>
<td width="350" align="left">
<div align="left">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
</div></td>
</tr>
<tr><Td></Td>
<Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
</tr>
<tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr>
<tr>
<td width="200"> </td>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200" align="center"><div align="left"></div></td>
<td width="100"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body></html>