نحوه ساختن Thumbnail برای تصاویر در php

amirepsilon

Active Member
سلام
برای ساختن thumb کد های زیر رو انجام بدید "لطفا"

PHP:
<?php 
function thumbnail_calcsize($w, $h, $square)
{
    $k = $square / max($w, $h);
    return array($w*$k, $h*$k);
}                            
?>

PHP:
<?php 
$params = array(array('size' => 200, // first thumbnail, should fit in square 200x200
                      'file' => 'thumbnail200.jpg'), // output file thumbnail200.jpg
                array('size' => 100, // second thumbnail, should fit in square 100x100
                      'file' => 'thumbnail100.jpg'), // output file thumbnail100.jpg
                array('size' => 50, // etc...
                      'file' => 'thumbnail50.jpg'));

// calling thumbnail_generator 
thumbnail_generator("source.jpg", $params);
?>

PHP:
<?php 

// don't forget to insert thumbnail_calcsize function (see above)

function thumbnail_generator($srcfile, &$params)
{
    // getting source image size
    @list($w, $h) = getimagesize($srcfile);
    if ($w == false)
        return false;

    // checking params array 
    if (!(is_array($params)&&is_array($params[0])))
        return false;

    $src = ImageCreateFromJpeg($srcfile);
    list($s1_w, $s1_h) = thumbnail_calcsize($w, $h, $params[0]['size']);

    // Create first thumbnail
    // Remember, first thumbnail should be largest thumbnail
    $img_s1 = imagecreatetruecolor($s1_w, $s1_h);
    imagecopyresampled($img_s1, $src, 0, 0, 0, 0, $s1_w, $s1_h, $w, $h);
    imagedestroy($src); // Destroy source image 


    // Other thumbnails are just downscaled copies of the first one
    for($i=1; $i<sizeof($params); $i++)
    {
        list($cur_w, $cur_h) = thumbnail_calcsize($w, $h, $params[$i]['size']);
        $img_cur = imagecreatetruecolor($cur_w, $cur_h);
        imagecopyresampled($img_cur, $img_s1, 0, 0, 0, 0, $cur_w, $cur_h, $s1_w, $s1_h);
        imagejpeg($img_cur, $params[$i]['file'], 90);
        imagedestroy($img_cur);
    }

    // Saving first thumbnail 
    imagejpeg($img_s1, $params[0]['file'], 90);
    imagedestroy($img_s1);
    return true;
}
?>

PHP:
<?php 
// Don't forget to change next two variables
// Or create web-server writable directory aeupload in 
// the directory with this php file

$upload_dir = "aeupload"; // Directory for file storing
                          // filesystem path

$web_upload_dir = "aeupload"; // Directory for file storing
                              // web-server dir 

/* upload_dir is filesystem path, something like 
   /var/www/htdocs/files/upload or c:/www/files/upload 
 
   web upload dir, is the webserver path of the same 
   directory. If your upload-directory accessible under  
   www.your-domain.com/files/upload/, then  
   web_upload_dir is /files/upload 
*/


// testing upload dir 
// remove these lines if you're sure 
// that your upload dir is really writable to PHP scripts
$tf = $upload_dir.'/'.md5(rand()).".test";
$f = @fopen($tf, "w");
if ($f == false)
    die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}' 
         or something like this");
fclose($f);
unlink($tf);
// end upload dir testing 

// * * * * * 
// INSERT SOURCE CODE OF thumbnail_calcsize() AND thumbnail_generator() HERE 
// * * * * *

// Upload processing part: 
if (isset($_FILES['file']) && ($_FILES['file']['size'] > 0))
{
    $u_filename = basename($_FILES['file']['name']);
    move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$u_filename);

    // Setting params array for thumbnail_generator 
    $params = array(array('size' => 220,
                          'file' => $upload_dir.'/s1-'.$u_filename),
                    array('size' => 140,
                          'file' => $upload_dir.'/s2-'.$u_filename),
                    array('size' => 80,
                          'file' => $upload_dir.'/s3-'.$u_filename));

    if (thumbnail_generator($upload_dir.'/'.$u_filename, $params) == false)
        die("Error processing uploaded file {$u_filename}");

    // ok, redirecting 
    // same host (HTTP_HOST), same script (PHP_SELF)
    // add ?file=filename parameter
    header("Location: http://{$_SERVER['HTTP_HOST']}{$PHP_SELF}?file={$u_filename}");
    exit();
}
// Upload processing end 
?> 
<html><head> 
<title>PHP multiple thumbnail generator</title> 
</head><body> 
<?php
if (!isset($_GET['file'])) {
// Following HTML code is outputed when user just loads this page
?> 
<h1>Upload image:</h1> 

<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data"> 

<script type="text/javascript"> 
/* This function is called when user selects file in file dialog */ 
function checkext(upload_field) 
{ 
    // this is just an example of checking  
    // image file extension - jpg/jpeg 

    var re_text = /\.jpeg|\.jpg/i; 
    var filename = upload_field.value; 

    /* Checking file type */ 
    if (filename.search(re_text) == -1) 
    { 
        alert("Please select JPEG file"); 
        upload_field.value = ''; 
    } 
    return true; 
} 
</script> 

Select jpeg photo: 
<input type="file" name="file" id="file" onChange="return checkext(this)"> 

<br><br>
<input type="submit"  value="upload & generate thumbnails"> 
</form> 
<?php
}
else {
// And this HTML code is shown when image was uploaded
$file = $_GET['file'];
?> 
<h1>Photo: <?php echo $file; ?></h1> 

<div align="center"> 
<!-- Outputting thumbnails -->
<img src="<?php echo $web_upload_dir.'/s1-'.$file; ?>"> 
<img src="<?php echo $web_upload_dir.'/s2-'.$file; ?>"> 
<img src="<?php echo $web_upload_dir.'/s3-'.$file; ?>"> 
<br><br> 
<!-- Outputting uploaded photo -->
<img src="<?php echo $web_upload_dir.'/'.$file; ?>"> 
</div> 
<?php
}
?> 
<br><br><br> 
Example by <a href="http://www.anyexample.com/">AnyExample</a> 
</body> 
</html>
?>
فقط چند نکته رو توجه داشته باشید :1. معمولا php بیش از 2 مگ رو نمیتونه آپلود کنه / اگه میخواهید بیشتر اپلود کنید بایدhttp://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize رو ببینید !2. در تگ فرم enctype="multipart/form-data" رو فراموش نکنید.3. یا علی :D
 

my friend

Member
ممنون بابت آموزش ، اما:
معمولا php بیش از 2 مگ رو نمیتونه آپلود کنه
شاید بهتر بود میگفتید به طور پیشفرض در php نمیشه فایل های بیشتر از 2 مگ رو آپلود کرد...
این لحن گفتن شما یه جورایی به خواننده القا میکنه که PHP در این مورد ضعف داره و اگه طرف مبتدی باشه دلسرد میشه...
باز هم ممنون.
 

alireza82

Well-Known Member
البته این میزان کاملا دست خودتون هست و قابل تنظیم!
پیش فرضش 2 مگ هست!
 

stalker

Member
راستش من خیلی از کد بالا سر در نیووردم (بذارید به حساب مبتدی بودنم )
اما کدی رو پیدا کردم که حد اقل برای ادم های مبتدی مثل من خیلی واضح و خوبه
لینک زبان اصلیش اینجاست
به زودی ترجمه فارسی اش رو همین جا میذارم
 

farik

Well-Known Member
دوستان ميشه يكم در مورد اينكه اين Thumbnail چيه توضيح بدين؟
 

alireza82

Well-Known Member
دوستان ميشه يكم در مورد اينكه اين Thumbnail چيه توضيح بدين؟

تو کتاب های فارسی به اسم بند انگشتی ترجمه میشن معمولا! در اصل نمایه ای از یک تصویر بزرگتر هستند مثلا شما یه تصویر 1200 در 1200 پیکسل داری خوب حالا یه تصویر کوچیکتر مثلا 100 در 100 ازش درست میکنی به این کوچیکتره میگن بند انگشتی!
امیدوارم موضوع رو رسونده باشم
 

irdavidnet

Banned
از این کد استفاده کنید : یک آدرس می دید بهش ، thumb رو با GD براتون ایجاد می کنه :
PHP:
<?php 
/**  
 * thumb.php?img=../../images/logo.jpg&h=200   --> resize to 200px height 
 * thumb.php?img=../../images/logo.jpg&&w=200&h=200   --> resize to 200px height & wieght
 * thumb.php?img=../../images/logo.jpg -->  normal picture size
 * www.iroveb.com ::: David Mozafari
 */ 
  
  
// Constants 
define('DEF_WIDTH',     150);  // default 
define('DEF_HEIGHT',    150);  // default 
define('ALLOWED_WIDTH', 1024); // no tampering: set up a max 
define('ALLOWED_HEIGHT',968);  // no tampering: set up a max 
define('DEF_QUALITY',   90);   // default quality 
  
define('DEBUG', false); 
  
  
// I put this here to avoid any external dependency 
if(!function_exists('__clean')) { 
  function __clean($s, $len){ 
      if(!isset($s)) return null; 
      $s = substr($s, 0, $len); 
      if(ini_get('gpc_magic_quotes') != 1) $s = addslashes($s); 
      $s = escapeshellcmd($s); 
      return $s; 
  } 
} 
  
// Get image location if not defined elsewhere 
if(!isset($image_path))  $image_path = urldecode(stripslashes(__clean($_GET['img'], 256))); 
if(!isset($width))       $width      = __clean($_GET['w'], 4); 
if(!isset($height))      $height     = __clean($_GET['h'], 4); 
  
// if both are not defined: 
if(!$width && !$height) { 
  $width = DEF_WIDTH; 
  $height= DEF_HEIGHT; 
} 
  
if($width) $width   =  min(ALLOWED_WIDTH, $width); 
else $width = ALLOWED_WIDTH; 
if($height) $height =  min(ALLOWED_HEIGHT, $height); 
else $height = ALLOWED_HEIGHT; 
  
  
define('MAX_HEIGHT', $height); 
define('MAX_WIDTH' , $width); 
  
  
// Load image 
$img = null; 
$imginfo = getimagesize($image_path); 
$imgtype = $imginfo[2]; 
  
$ext = strtolower(end(explode('.', $image_path))); 
if ($imgtype == IMAGETYPE_JPEG) { 
    $img = @imagecreatefromjpeg($image_path); 
} else if ($imgtype == IMAGETYPE_PNG) { 
    $img = @imagecreatefrompng($image_path); 
    //echo "IMGEBASE " . IMAGE_BASE . ' path: ' .  $image_path; exit; 
// Only if your version of GD includes GIF support 
} else if ($imgtype == IMAGETYPE_GIF) { 
    $img = @imagecreatefromgif($image_path); 
} 
  
// If an image was successfully loaded, test the image for size 
if ($img) { 
  
    // Get image size and scale ratio 
    $width = imagesx($img); 
    $height = imagesy($img); 
    $scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height); 
    if(defined('DEBUG') && DEBUG) { 
      user_error("thumb.php - IMAGE: $image_path  WIDTH: $width HEIGHT: $height SCALE: $scale<hr />"); 
      exit; 
    } 
  
    // If the image is larger than max shrink it 
    if ($scale < 1) { 
        $new_width = floor($scale*$width); 
        $new_height = floor($scale*$height); 
  
        // Create a new temporary image 
        $tmp_img = imagecreatetruecolor($new_width, $new_height); 
  
        // Copy and resize old image into new image 
        imagecopyresized($tmp_img, $img, 0, 0, 0, 0, 
                         $new_width, $new_height, $width, $height); 
        imagedestroy($img); 
        $img = $tmp_img; 
    } 
} 
  
// Create error image if necessary 
if (!$img) { 
    $img = imagecreate(DEF_WIDTH, DEF_HEIGHT); 
    imagecolorallocate($img,255,255,255); 
    $c2 = imagecolorallocate($img,255,0,0); 
    imageline($img,0,0,DEF_WIDTH,DEF_HEIGHT,$c2); 
    imageline($img,DEF_WIDTH,0,0,DEF_HEIGHT,$c2); 
} 
  
if(!$jpgfilename) { 
  // Display the image 
  header("Content-type: image/jpg"); 
  imagejpeg($img, null, DEF_QUALITY); 
  exit; 
} else { 
   if(defined('DEBUG') && DEBUG) { 
      echo "thumb.php - saving to $jpgfilename<hr>"; 
  } 
  imagejpeg($img, $jpgfilename, DEF_QUALITY); 
} 
?>
این دکمه تشکر رو بزنی بد نیست .
 

irdavidnet

Banned
الان یه مشکلی دارم توی این اسکریپت بندانگشتی من ،
روی سرور این تابع رو بستن ، escapeshellcmd چه کنم ؟
جایگزینی داره ؟
 

alireza82

Well-Known Member
escapeshellcmd یک تابع امنیتی هست برا چی بستن! برا وفتی هست که از توابع exec و system استفاده مکنید ، این میاد از اجرای شل های مخرب جلوگیری میکنه!
ولی مدیر سرور نابقه هست اگر این رو ببنده ، اگر میخواست ببنده باید exec یا system رو میبست نه این رو:)
 

zoghal

Active Member
هر دو اسکریپت بر روی لوکال جواب نداد. gd فعال هست و سایر اسکریپت ها هم جواب میدن
 

جدیدترین ارسال ها

بالا