Jump to content

created two versions of image in folder


samoht

Recommended Posts

I was wonder if I could get some help on putting together a script that would loop through all the images in a folder and created two other images (a thumbnail and a largesize) for each image?

 

I have :

<?php
/*
Create a thumbnail of $srcFile and save it to $destFile.
The thumbnail will be $width pixels.
*/
function createThumbnail($srcFile, $destFile, $width, $quality = 150)
{
$thumbnail = '';

if (file_exists($srcFile)  && isset($destFile))
{
	$size        = getimagesize($srcFile);
	$w           = number_format($width, 0, ',', '');
	$h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

	$thumbnail =  copyImage($srcFile, $destFile, $w, $h, $quality);
}

// return the thumbnail file name on sucess or blank on fail
return basename($thumbnail);
}

/*
Create a fullsize image of $srcFile and save it to $destFile.
The fullsize image  will be $width pixels.
*/
function createFullsize($srcFile, $destFile, $width, $quality = 350)
{
$fullsize = '';

if (file_exists($srcFile)  && isset($destFile))
{
	$size        = getimagesize($srcFile);
	$w           = number_format($width, 0, ',', '');
	$h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');

	$fullsize =  copyImage($srcFile, $destFile, $w, $h, $quality);
}

// return the thumbnail file name on sucess or blank on fail
return basename($fullsize);
}
/*
Copy an image to a destination file. The destination
image size will be $w X $h pixels
*/
function copyImage($srcFile, $destFile, $w, $h, $quality = 150)
{
    $tmpSrc     = pathinfo(strtolower($srcFile));
    $tmpDest    = pathinfo(strtolower($destFile));
    $size       = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
       $destFile  = substr_replace($destFile, 'jpg', -3);
       $dest      = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
       $dest = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } else {
      return false;
    }

    switch($size[2])
    {
       case 1:       //GIF
           $src = imagecreatefromgif($srcFile);
           break;
       case 2:       //JPEG
           $src = imagecreatefromjpeg($srcFile);
           break;
       case 3:       //PNG
           $src = imagecreatefrompng($srcFile);
           break;
       default:
           return false;
           break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
       case 1:
       case 2:
           imagejpeg($dest,$destFile, $quality);
           break;
       case 3:
           imagepng($dest,$destFile);
    }
    return $destFile;

}

 

But I am not sure how to write the function that calls these and names the two new images by concatenating a tn and a fs to the end of the image name?

 

also, I'm not sure if the above code is correct for making two copies??

 

Any Ideas?

 

 

Link to comment
Share on other sites

I have a page doing just this on one of my sites, here is the code I am using. There is a bit of gobbly goob in there from my paticular site but the resize code is pretty clear. jpegs only, Hope it helps...

 

$piccheck = mysql_query("SELECT * FROM users WHERE username = '$username'", GetMyConnection() )or die(mysql_error());
$picinfo = mysql_fetch_array($piccheck);
$pic1 = $picinfo['picname1'];
$pic2 = $picinfo['picname2'];
$thpic1 = $picinfo['thpicname1'];
$thpic2 = $picinfo['thpicname2'];

function getFileExtension($str) {

        $i = strrpos($str,".");
        if (!$i) { return ""; }

        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);

        return $ext;

    }

$maxfilesize=204800;

if($_POST['submit']){

if ($_POST['agreed'] == "pic1") {
	if ($pic1){
	mysql_query("UPDATE users SET picname1 = '' WHERE username = '$username'", GetMyConnection() )or die(mysql_error());
	mysql_query("UPDATE users SET thpicname1 = '' WHERE username = '$username'", GetMyConnection() )or die(mysql_error());
	unlink("userimages/".$pic1);
	unlink("userimages/".$thpic1);
	}

        $size = 100; // the thumbnail height   
	$sizew = 100; //the thumbnail width
	$fsize = 480; // the full size pic height
	$fsizew = 640; //the full size width
        $filedir = 'userimages/'; // the directory for the full size image   
        $thumbdir = 'userimages/'; // the directory for the thumbnail image   
        $prefix = 'th_'.$username; // the prefix to be added to the original name for thumbnail
	$fprefix = $username; //the prefix to be added to the full size pic	
        $maxfile = '204800';   
        $mode = '0666';   
        $userfile_name = $_FILES['image']['name'];   
        $userfile_tmp = $_FILES['image']['tmp_name'];   
        $userfile_size = $_FILES['image']['size'];   
        $userfile_type = $_FILES['image']['type'];   
        if (isset($_FILES['image']['name']))    
        { 

		$pext = getFileExtension($userfile_name);
		$pext = strtolower($pext);
		if (($pext != "jpg")  && ($pext != "jpeg"))	{
		print "<h1>ERROR</h1>Image Extension Unknown.<br>";
		print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>";
		print "The file you uploaded had the following extension: $pext</p>\n";
		/*== delete uploaded file ==*/
		unlink($userfile_tmp);
		exit();
		}

            $prod_img = $filedir.$username.$userfile_name;   
            $prod_img_thumb = $thumbdir.$prefix.$userfile_name;   
            move_uploaded_file($userfile_tmp, $prod_img);   
            chmod ($prod_img, octdec($mode));

		//Resize the full image to max width 640 or max height 480	
		$sizes = getimagesize($prod_img);   
            $aspect_ratio = $sizes[1]/$sizes[0];    
            if ($sizes[1] <= $fsize && $sizes[0] <= $fsizew)   
            {   
                 $new_width = $sizes[0];   
                 $new_height = $sizes[1];   
		}elseif ($sizes[1] <= $fsize && $sizes[0] > $fsizew)
		{   
                $new_width = $fsizew;
			$new_height = abs($new_width/$aspect_ratio);
		}elseif ($sizes[1] <= $sizes[0])
		{
			$aspect_ratio = $sizes[0]/$sizes[1];
			$new_width = $fsizew;
			$new_height = abs($new_width/$aspect_ratio);
		}else
		{
			$new_height = $fsize;   
                $new_width = abs($new_height/$aspect_ratio); 
		}
            $destimg=ImageCreateTrueColor($new_width,$new_height)   
                or die('Problem In Creating image');   
            $srcimg=ImageCreateFromJPEG($prod_img)   
                or die('Problem In opening Source Image');   
            if(function_exists('imagecopyresampled'))   
            {   
                imagecopyresampled($destimg,$srcimg,0,0,0,0,   
                   $new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))   
                or die('Problem In resizing');   
            }else{   
                Imagecopyresized($destimg,$srcimg,0,0,0,0,   
                   $new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))   
                or die('Problem In resizing');   
            }   
            ImageJPEG($destimg,$prod_img,90)   
                or die('Problem In saving');   
            imagedestroy($destimg);   
         



            $sizes = getimagesize($prod_img);   
            $aspect_ratio = $sizes[1]/$sizes[0];    
            if ($sizes[1] <= $size && $sizes[0] <= $sizew)   
            {   
                 $new_width = $sizes[0];   
                 $new_height = $sizes[1];   
		}elseif ($sizes[1] <= $size && $sizes[0] > $sizew)
		{   
                $new_width = $sizew;
			$new_height = abs($new_width/$aspect_ratio);
		}elseif ($sizes[1] <= $sizes[0])
		{
			$aspect_ratio = $sizes[0]/$sizes[1];
			$new_width = $sizew;
			$new_height = abs($new_width/$aspect_ratio);
		}else
		{
			$new_height = $size;   
                $new_width = abs($new_height/$aspect_ratio); 
		}
            $destimg=ImageCreateTrueColor($new_width,$new_height)   
                or die('Problem In Creating image');   
            $srcimg=ImageCreateFromJPEG($prod_img)   
                or die('Problem In opening Source Image');   
            if(function_exists('imagecopyresampled'))   
            {   
                imagecopyresampled($destimg,$srcimg,0,0,0,0,   
                   $new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))   
                or die('Problem In resizing');   
            }else{   
                Imagecopyresized($destimg,$srcimg,0,0,0,0,   
                   $new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))   
                or die('Problem In resizing');   
            }   
            ImageJPEG($destimg,$prod_img_thumb,90)   
                or die('Problem In saving');   
            imagedestroy($destimg);   
        } 
	$userfilename=$username.$userfile_name;
	$thuserfilename=$prefix.$userfile_name;

	mysql_query("UPDATE users SET picname1 = '$userfilename' WHERE username = '$username'", GetMyConnection() )or die(mysql_error());
	mysql_query("UPDATE users SET thpicname1 = '$thuserfilename' WHERE username = '$username'", GetMyConnection() )or die(mysql_error());

        CleanUpDB();

Link to comment
Share on other sites

What I am thinking is cross referencing the images by name in your database, so when an image is added to your image folder it's name is added to the database. This makes it easy to display, work with, and and manipulate them any way you want to. Instead of searching and working with image name from the actual folder, you are just cross referencing it from the database entry.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.