Page 1 of 1

Resize the images on upload

Posted: Tue Jan 19, 2010 8:47 pm
by avl8386
In the code it resizes and creates a thumbnail that is 120x120 and saves it. The original image is left the same size. I need the script to scale the original imge to 640x480 and save it instead of saving it in the original size.

Can anyone help>

Code: Select all

 
<?php
include 'includes/common.inc.php';
 
if (!$user->logged_in)
{
    //if your not logged in you shouldn't be here
    header("location: user_login.php");
    exit;
}
 
$cropdefault = false;
$width = $system->SETTINGS['thumb_show'];
$height = $width / 1.2;
 
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale)
{
    list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    $imageType = image_type_to_mime_type($imageType);
    // some error checks
    $start_width = ($start_width < 0) ? 0 : $start_width;
    $start_height = ($start_height < 0) ? 0 : $start_height;
    $width = ($imagewidth < $width) ? $imagewidth : $width;
    $height = ($imageheight < $height) ? $imageheight : $height;
    if (($width + $start_width) > $imagewidth)
    {
        $start_width = $imagewidth - $width;
    }
    if (($height + $start_height) > $imageheight)
    {
        $start_height = $imageheight - $height;
    }
 
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
    $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
    switch ($imageType)
    {
        case 'image/gif':
            $source = imagecreatefromgif ($image);
            break;
        case 'image/pjpeg':
        case 'image/jpeg':
        case 'image/jpg':
            $source = imagecreatefromjpeg($image);
            break;
        case 'image/png':
        case 'image/x-png':
            $source = imagecreatefrompng($image);
            break;
    }
    imagecopyresampled($newImage, $source, 0, 0, $start_width, $start_height, $newImageWidth, $newImageHeight, $width, $height);
    switch ($imageType)
    {
        case 'image/gif':
            imagegif ($newImage, $thumb_image_name);
            break;
        case 'image/pjpeg':
        case 'image/jpeg':
        case 'image/jpg':
            imagejpeg($newImage, $thumb_image_name, 90);
            break;
        case 'image/png':
        case 'image/x-png':
            imagepng($newImage, $thumb_image_name);
            break;
    }
    chmod($thumb_image_name, 0777);
    return $thumb_image_name;
}
 
// Process delete
if ($_GET['action'] == 'delete' && isset($_GET['img']))
{
    if ($_SESSION['SELL_pict_url_temp'] == $_SESSION['UPLOADED_PICTURES'][intval($_GET['img'])])
    {
        unlink($upload_path . session_id() . '/' . $_SESSION['SELL_pict_url']);
        unset($_SESSION['SELL_pict_url']);
    }
    unlink($upload_path . session_id() . '/' . $_SESSION['UPLOADED_PICTURES'][intval($_GET['img'])]);
    unset($_SESSION['UPLOADED_PICTURES'][intval($_GET['img'])]);
    unset($_SESSION['UPLOADED_PICTURES_SIZE'][intval($_GET['img'])]);
}
 
if ($_GET['action'] == 'makedefault')
{
    $cropdefault = true;
    $image = $_GET['img'];
}
 
if ($_GET['action'] == 'crop' && !empty($_POST['w']))
{
    if ($_POST['upload_thumbnail'] == $MSG['616'])
    {
        // Get the new coordinates to crop the image.
        $x1 = intval($_POST['x1']);
        $y1 = intval($_POST['y1']);
        $x2 = intval($_POST['x2']);
        $y2 = intval($_POST['y2']);
        $w = intval($_POST['w']);
        $h = intval($_POST['h']);
        // Scale the image to the thumb_width set above
        $scale = $width / $w;
        $large_image_location = $upload_path . session_id() . '/' . $_GET['img'];
        $thumb_image_location = $upload_path . session_id() . '/thumb-' . $_GET['img'];
        $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location, $w, $h, $x1, $y1, $scale);
        $_SESSION['SELL_pict_url'] = 'thumb-' . $_GET['img'];
        $_SESSION['SELL_pict_url_temp'] = $_GET['img'];
    }
    else
    {
        $_SESSION['SELL_pict_url_temp'] = $_SESSION['SELL_pict_url'] = $_GET['img'];
    }
}
 
// close window
if (!empty($_POST['creategallery']))
{
    $_SESSION['GALLERY_UPDATED'] = true;
    print '<script type="text/javascript">window.close()</script>';
    exit;
}
 
// PROCESS UPLOADED FILE
if ($_POST['uploadpicture'] == $MSG['681'])
{
    if (!empty($_FILES['userfile']['tmp_name']) && $_FILES['userfile']['tmp_name'] != 'none')
    {
        if (!isset($_SESSION['UPLOADED_PICTURES']) || !is_array($_SESSION['UPLOADED_PICTURES'])) $_SESSION['UPLOADED_PICTURES'] = array();
        if (!isset($_SESSION['UPLOADED_PICTURES_SIZE']) || !is_array($_SESSION['UPLOADED_PICTURES_SIZE'])) $_SESSION['UPLOADED_PICTURES_SIZE'] = array();
        $filename = $_FILES['userfile']['name'];
        $nameparts = explode('.', $filename);
        $file_ext = $nameparts[count($nameparts) - 1];
        $file_types = array('gif', 'jpg', 'jpeg', 'png', 'GIF', 'JPG', 'JPEG', 'PNG');
 
        if ($_FILES['userfile']['size'] > $system->SETTINGS['maxuploadsize'])
        {
            $ERR = $ERR_709 . '&nbsp;' . ($system->SETTINGS['maxuploadsize'] / 1024) . '&nbsp;' . $MSG['672'];
        }
        elseif (!in_array($file_ext, $file_types))
        {
            $ERR = $ERR_710 . ' (' . $file_ext . ')';
        }
        elseif (in_array($_FILES['userfile']['name'], $_SESSION['UPLOADED_PICTURES']))
        {
            $ERR = $MGS_2__0054 . ' (' . $_FILES['userfile']['name'] . ')';
        }
        else
        {
            // Create a TMP directory for this session (if not already created)
            if (!file_exists($upload_path . session_id()))
            {
                umask(0);
                mkdir($upload_path . session_id(), 0777);
                chmod($upload_path . session_id(), 0777); //incase mkdir fails
            }
            // Move uploaded file into TMP directory & rename
            $replace = array('.', ' ', ',');
            // clean the file
            $newname = str_replace('.' . $file_ext, '', $filename);
            $newname = str_replace($replace, '_', $newname) . '.' . $file_ext;
            if ($system->move_file($_FILES['userfile']['tmp_name'], $upload_path . session_id() . '/' . $newname))
            {
                // Populate arrays
                array_push($_SESSION['UPLOADED_PICTURES'], $newname);
                $fname = $upload_path . session_id() . '/' . $newname;
                array_push($_SESSION['UPLOADED_PICTURES_SIZE'], filesize($fname));
                if (count($_SESSION['UPLOADED_PICTURES']) == 1)
                {
                    $cropdefault = true;
                    $image = $newname;
                }
            }
        }
    }
}
 
if ($cropdefault)
{
    list($imgwidth, $imgheight) = getimagesize($upload_path . session_id() . '/' . $image);
    $swidth = ($imgwidth < 380) ? '' : ' width: 380px;';
    $imgratio = ($imgwidth > 380) ? $imgwidth / 380 : 1;
    $startX = $imgwidth;
    $startY = $imgheight;
    if ($imgwidth > $imgheight)
    {
        $ratio = '1.2:1';
        $thumbwh = 'width:' . $width . '; height:' . $height . ';';
        $scaleX = 120;
        $scaleY = 100;
        $startX = $startY * 1.2;
    }
    else
    {
        $ratio = '1:1.2';
        $thumbwh = 'height:' . $width . '; width:' . $height . ';';
        $scaleX = 100;
        $scaleY = 120;
        $startY = $startX * 1.2;
    }
 
    $template->assign_vars(array(
            'RATIO' => $ratio,
            'THUMBWH' => $thumbwh,
            'SCALEX' => $scaleX,
            'SCALEY' => $scaleY,
            'IMGRATIO' => $imgratio,
            'SWIDTH' => $swidth,
            'IMGWIDTH' => $imgwidth,
            'IMGHEIGHT' => $imgheight,
            'IMGPATH' => $uploaded_path . session_id() . '/' . $image,
            'STARTX' => $startX,
            'STARTY' => $startY,
            'IMAGE' => $image
            ));
}
else
{
    $template->assign_vars(array(
            'MAXIMAGES' => $system->SETTINGS['maxpictures'],
            'ERROR' => (isset($ERR)) ? $ERR : '',
 
            'B_CANUPLOAD' => (!isset($_SESSION['UPLOADED_PICTURES']) || count($_SESSION['UPLOADED_PICTURES']) < $system->SETTINGS['maxpictures'])
            ));
}
 
foreach ($_SESSION['UPLOADED_PICTURES'] as $k => $v)
{
    $template->assign_block_vars('images', array(
            'IMGNAME' => $v,
            'IMGSIZE' => $_SESSION['UPLOADED_PICTURES_SIZE'][$k],
            'ID' => $k,
            'DEFAULT' => ($v == $_SESSION['SELL_pict_url_temp']) ? 'selected.gif' : 'unselected.gif'
            ));
}
 
if ($system->SETTINGS['fees'] == 'y')
{
    $query = "SELECT value FROM " . $DBPrefix . "fees WHERE type = 'picture_fee'";
    $res = mysql_query($query);
    $system->check_mysql($res, $query, __LINE__, __FILE__);
    $image_fee = mysql_result($res, 0);
}
else
{
    $image_fee = 0;
}
 
// get decimals for javascript rounder
$decimals = '';
for ($i = 0; $i < $system->SETTINGS['moneydecimals']; $i++)
{
    $decimals .= 0;
}
 
$template->assign_vars(array(
        'SITENAME' => $system->SETTINGS['sitename'],
        'THEME' => $system->SETTINGS['theme'],
        'HEADERCOLOUR' => $system->SETTINGS['headercolor'],
        'NUMIMAGES' => count($_SESSION['UPLOADED_PICTURES']),
        'IMAGE_COST' => $image_fee,
        'FEE_DECIMALS' => $decimals,
 
        'B_CROPSCREEN' => $cropdefault
        ));
$template->set_filenames(array(
        'body' => 'upldgallery.tpl'
        ));
$template->display('body');
?>
 
 

Re: Resize the images on upload

Posted: Tue Jan 19, 2010 9:04 pm
by requinix
So create a thumbnail that's 640x480 and overwrite the original image.

Re: Resize the images on upload

Posted: Tue Jan 19, 2010 9:46 pm
by avl8386
i need the thumbnail for other parts of the site. the original image is loaded after the user clicks the thumbnail. Some of the images are 2300x???? so you click them and they take up more than the screen.

I am not very good with php at all that is why u am here asking for help

Re: Resize the images on upload

Posted: Tue Jan 19, 2010 11:09 pm
by requinix
avl8386 wrote:i need the thumbnail for other parts of the site. the original image is loaded after the user clicks the thumbnail. Some of the images are 2300x???? so you click them and they take up more than the screen.

I am not very good with php at all that is why u am here asking for help
Okay... And?

Lines 95-106 make one thumbnail. If you want another one, copy those lines and make changes as necessary.

Re: Resize the images on upload

Posted: Wed Jan 20, 2010 7:47 am
by avl8386
That is why i am here. i am php impaired. i need to know what in those lines to change and what other lines to get rid of so i dont have 3 images in the folder only the two resized images

Re: Resize the images on upload

Posted: Wed Jan 20, 2010 7:52 am
by Eran
Do you know any PHP at all?

Re: Resize the images on upload

Posted: Wed Jan 20, 2010 10:09 am
by avl8386
not much i am just starting to learn it. I have read a few things i just am not real good with it at all. It is a whole new field to me.

I am going to try and edit the code like you said and see if i can figure it out

Re: Resize the images on upload

Posted: Wed Jan 20, 2010 3:20 pm
by avl8386
OK i am completely lost.

I dont get how it is getting the variables as to what size to save the thumbnail.

Where in the code is it saving the original??

Re: Resize the images on upload

Posted: Wed Jan 20, 2010 4:35 pm
by stoshrocket
avl8386 wrote:OK i am completely lost.

I dont get how it is getting the variables as to what size to save the thumbnail.

Where in the code is it saving the original??
The function that resizes and saves the thumbnail is between lines 16-70. Let's deconstruct it a little further so you understand:

Lines 18-35:

Code: Select all

 
    list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    $imageType = image_type_to_mime_type($imageType);
    // some error checks
    $start_width = ($start_width < 0) ? 0 : $start_width;
    $start_height = ($start_height < 0) ? 0 : $start_height;
    $width = ($imagewidth < $width) ? $imagewidth : $width;
    $height = ($imageheight < $height) ? $imageheight : $height;
    if (($width + $start_width) > $imagewidth)
    {
        $start_width = $imagewidth - $width;
    }
    if (($height + $start_height) > $imageheight)
    {
        $start_height = $imageheight - $height;
    }
 
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
 
This just deals with the variables inputted into the function, deals with some error checks and scales the image width/height to prepare the variables for the thumbnail.

Lines 36-51:

Code: Select all

 
    $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
    switch ($imageType)
    {
        case 'image/gif':
            $source = imagecreatefromgif ($image);
            break;
        case 'image/pjpeg':
        case 'image/jpeg':
        case 'image/jpg':
            $source = imagecreatefromjpeg($image);
            break;
        case 'image/png':
        case 'image/x-png':
            $source = imagecreatefrompng($image);
            break;
    }
 
This creates a new image with the dimensions "$newImageWidth, $newImageHeight" and opens up the original image ready to be copied and scaled in the next stage...

Lines 52-69:

Code: Select all

 
    imagecopyresampled($newImage, $source, 0, 0, $start_width, $start_height, $newImageWidth, $newImageHeight, $width, $height);
    switch ($imageType)
    {
        case 'image/gif':
            imagegif ($newImage, $thumb_image_name);
            break;
        case 'image/pjpeg':
        case 'image/jpeg':
        case 'image/jpg':
            imagejpeg($newImage, $thumb_image_name, 90);
            break;
        case 'image/png':
        case 'image/x-png':
            imagepng($newImage, $thumb_image_name);
            break;
    }
    chmod($thumb_image_name, 0777);
    return $thumb_image_name;
 
This copies the original image we just opened, with all the new attributes thereby creating the thumbnail, which is then saved according to what type image we are dealing with. The image is then chmod'd and the thumbnail image name returned.

This function just needs to be altered slightly to create two images, one thumbnail and one resized one to your specific dimensions, and then renaming or deleting the old one.

See if you can figure this one out now...

PS: php.net will help :P

Re: Resize the images on upload

Posted: Thu Jan 21, 2010 9:19 pm
by avl8386
I gave up on it.. I am gonna have to buy a php book or two when i get paid next week sit down and absorb. I am trying to go into this without knowing a thing about it. I was jsut hoping someone could do this for me so i could get this site launched but it will just have to wait till i can figure it out.

Can anyone recommend some good books to learn from? I don't want books that give you stupid tutorials that get you nowhere. I have looked at alot that give you hello world scripts and stupid layout scripts. I need a deep down learning experience.