Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts

    Trying to Reduce Image Size and Preserve Transparency

    I have set up a database of entities (for lack of a better term, they will mostly be companies) and given the user the ability to upload an associated image of the entity's logo (for instance Nike would have their Swoosh). Early on I recognized that on the entity page I mostly want a small thumbnail version of the logo and it might as well be a small resolution version to save bandwidth.

    At this point I have gotten PHP to make smaller thumbnail versions (smaller in resolution and in KB used) BUT for some reason I am having serious issues preserving the transparency of GIF and PNG images. For instance this original image:



    Turns into the following:



    But the original file has transparency. What am I doing wrong? I would like to use the transparency that is already set for the original image and I'm not sure how to acquire that information. Here is my code:

    PHP Code:
    function createThumbnail_png($img$imgPath$suffix$newWidth$newHeight$quality)
    {
      
    // Open the original image.
      
    $original imagecreatefrompng("$imgPath/$img") or die("Error Opening original");

      list(
    $width$height$type$attr) = getimagesize("$imgPath/$img");
     
      
    // Resample the image.
      
    $tempImg imagecreatetruecolor($newWidth$newHeight) or die("Cant create temp image");
      
    imagecopyresized($tempImg$original0000$newWidth$newHeight$width$height) or die("Cant resize copy");
      
    $background imagecolorallocate($tempImg000);
      
    imagecolortransparent($tempImg$background);
      
    imagealphablending($tempImgfalse);
      
    imagesavealpha($tempImgtrue);
     
      
    // Create the new file name.
      
    $newNameE explode("."$img);
      
    $newName ''$newNameE[0] .''$suffix .'.'$newNameE[1] .'';
     
      
    // Save the image.
      
    imagepng($tempImg"$imgPath/$newName"0) or die("Cant save image");
     
      
    // Clean up.
      
    imagedestroy($original);
      
    imagedestroy($tempImg);
      return 
    true;
    }

    function 
    createThumbnail_gif($img$imgPath$suffix$newWidth$newHeight$quality)
    {
      
    // Open the original image.
      
    $original imagecreatefromgif("$imgPath/$img") or die("Error Opening original");

      list(
    $width$height$type$attr) = getimagesize("$imgPath/$img");
     
      
    // Resample the image.
      
    $tempImg imagecreatetruecolor($newWidth$newHeight) or die("Cant create temp image");
      
    imagecopyresized($tempImg$original0000$newWidth$newHeight$width$height) or die("Cant resize copy");
      
    imagealphablending($tempImgtrue);
      
    imagesavealpha($tempImgtrue);
     
      
    // Create the new file name.
      
    $newNameE explode("."$img);
      
    $newName ''$newNameE[0] .''$suffix .'.'$newNameE[1] .'';
     
      
    // Save the image.
      
    imagegif($tempImg"$imgPath/$newName") or die("Cant save image");
     
      
    // Clean up.
      
    imagedestroy($original);
      
    imagedestroy($tempImg);
      return 
    true;

    Would there be an easier function that could inherently preserve transparency metadata? I don't think imagecopy() does though...
    Last edited by d'Anconia; 05-24-2012 at 04:12 AM.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,497
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    You're using pure black 0,0,0 or HEX 000000

    The image has that, and your background has that.

    How about if you make your background 1,1,1

    That won't be "pure black", but the human eye won't notice.
    Transparency will work because the RGB values won't be the same.

    EDIT:
    I think I read the post wrong.
    Nevermind if my answer doesn't make sense.


    .

  • #3
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Yeah unfortunately the background for the thumbnail is still coming as black. I need the transparency from the original to be preserved when creating the new one. Surely there must be some function to find the transparency value of the original image and then another function to insert that data / metadata into the new thumbnail. Or at least I would that such functions existed!
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Something's not right here with the painting of the background.
    First, lets talk about the gif. GD doesn't support animated gif's, so the first thing I'd do is never allow a save as a gif. May as well keep them all as png's since it will make it a lot easier.
    Here's the process: create a true color image, paint the background transparent. Copy and resize the original. Save as png. All done.

    I'm lazy, so I'll just open whatever image type and convert it to a png. I'd probably do something like this:
    PHP Code:
    <?php

    $sOriginal 
    'scaledown.png';
    $aImageInfo getimagesize($sOriginal);
    $iNewWidth $aImageInfo[0] / 4;
    $iNewHeight $aImageInfo[1] / 4;

    if (
    $sCreated createThumbnail($sOriginal'.''tmb'$iNewWidth$iNewHeight))
    {
        
    printf('<div style="width: 300; height: 300; background-color: #555;"><img src="%s" alt="" /></div>'$sCreated);
    }


    function 
    createThumbnail($sImageName$sImagePath$suffix$newWidth$newHeight$iQuality 9$bPreserveAlpha true)
    {
        
    $sResult '';
        if (
    $im imagecreatetruecolor($newWidth$newHeight))
        {
            if (
    $bPreserveAlpha)
            {
                
    $trans imagecolortransparent($im);
                
    imagefill($im00$trans);
                
    imagealphablending($imtrue);
                
    imagesavealpha($imtrue);
            }
            
    $sPath realpath($sImagePath '/' $sImageName);
            if (
    is_file($sPath) && is_readable($sPath))
            {
                if (
    $fp fopen($sPath'rb'))
                {
                    
    $sBinary '';
                    while (
    $r fread($fp8192))
                    {
                        
    $sBinary .= $r;
                    }
                    
    fclose($fp);
                    if (
    $original imagecreatefromstring($sBinary))
                    {
                        if (
    imagecopyresampled($im$original0000$newWidth$newHeightimagesx($original), imagesy($original)))
                        {
                            
    $sResult pathinfo($sPathPATHINFO_FILENAME) . $suffix '.png';
                            
    imagepng($im$sResult$iQuality);
                            
    imagedestroy($im);
                        }                
                    }
                }
            }
        }
        return 
    $sResult;
    }
    Last edited by Fou-Lu; 05-27-2012 at 06:03 PM. Reason: Changed to use a realpath instead

  • #5
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Fou-Lu, I appreciate your help but in all honesty I think your level of coding is much higher than mine so it is hard for me to understand all of it and customize for my needs.

    Is it possible to just use imagecopyresampled? Will that function maintain the transparency?
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    I don't think so, but lets double check.
    Nope definitely need to paint the transparent background first. One by one check says you don't need to use imagealphablending though, which I guess makes sense since the only blend for it will be transparent.

    What do you need to change on it? This one currently accept any type of image it can open with the imagecreatefromstring, resizes it and saves it as a png. The only thing I could suggest changing to it really is that if it detects the thumb already that it should return that thumb instead of attempting to resize and save a new one.

  • #7
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Fou-Lu, I'm not certain that anything needs to be changed in it. I am going to work on integrating it into my page for testing and I'll get back to you once I've put some good work into it. I've been travelling a lot this weekend.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Quote Originally Posted by d'Anconia View Post
    Fou-Lu, I'm not certain that anything needs to be changed in it. I am going to work on integrating it into my page for testing and I'll get back to you once I've put some good work into it. I've been travelling a lot this weekend.
    The function signature is compatible with the one you currently have as well, except that I removed the image type suffix. I added the preserveTransparency flag which defaults to true, so it doesn't need to be modified during a call either. The only other change is that I return a string for the filepath created (empty on failure) instead of a boolean, but can still be used in an if statement if desired since an empty string is considered false.
    For the most part it'll be seamless for integration minus the name difference. But as I mentioned you can't preserve the frames in a gif with gd (or I should say you couldn't and assume you still cannot), and to get around the true color to palette transparency its just easier to save as a png. So you can load a gif up and it will return a png thumbnail.

  • #9
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Fou-Lu, okay I am trying to integrate your code correctly but thus far it seems that my base image is being made but the thumbnail files are not being created. The function is in a separate file that is included at the very beginning of the script. Here is the snippet of code that utilizes the createThumbnail function:

    PHP Code:
    if (move_uploaded_file ($_FILES['upload']['tmp_name'], "entities/images/" $random_logo_name)) {
                
    //    
                                
    list($image_width$image_height$image_type$attr)= getimagesize("entities/images/" $random_logo_name); 
                                if (
    $image_width >= $image_height) {
                                        
    $width_ratio $image_width 150;
                                        
    $new_height $image_height $width_ratio;
                                        
    $new_width $image_width $width_ratio;
                                   }
                                   else {
                                            
    $height_ratio $image_height 150;
                                            
    $new_width $image_width $height_ratio;
                                            
    $new_height $image_height $height_ratio;
                                   }
                                switch (
    $exts) {
                                    case 
    'jpeg':
                                        
    createThumbnail($random_logo_name'/entities/images''_thumb' $new_width$new_height9true); 
                                        break;
                                    case 
    'jpg':
                                        
    createThumbnail($random_logo_name'/entities/images''_thumb' $new_width$new_height9true); 
                                        break;
                                    case 
    'gif':
                                        
    createThumbnail($random_logo_name'/entities/images''_thumb' $new_width$new_height9true);
                                        break;
                                    case 
    'png':
                                        
    createThumbnail($random_logo_name'/entities/images''_thumb' $new_width$new_height9true);
                                        break;
                                }
                                   
                                
                  echo 
    '<p><em>The file has been uploaded!</em></p>';
                } 
    // End of move... IF. 
    So specifically the function is called toward the end of that code. Here is what I have as the function right now:

    PHP Code:

    function createThumbnail($sImageName$sImagePath$suffix$newWidth$newHeight$iQuality 9$bPreserveAlpha true)
    {
        
    $sResult '';
        if (
    $im imagecreatetruecolor($newWidth$newHeight))
        {
            if (
    $bPreserveAlpha)
            {
                
    $trans imagecolortransparent($im);
                
    imagefill($im00$trans);
                
    imagealphablending($imtrue);
                
    imagesavealpha($imtrue);
            }
            
    $sPath realpath($sImagePath '/' $sImageName);
            if (
    is_file($sPath) && is_readable($sPath))
            {
                if (
    $fp fopen($sPath'rb'))
                {
                    
    $sBinary '';
                    while (
    $r fread($fp8192))
                    {
                        
    $sBinary .= $r;
                    }
                    
    fclose($fp);
                    if (
    $original imagecreatefromstring($sBinary))
                    {
                        if (
    imagecopyresampled($im$original0000$newWidth$newHeightimagesx($original), imagesy($original)))
                        {
                            
    $sResult pathinfo($sPathPATHINFO_FILENAME) . $suffix '.png';
                            
    imagepng($im$sResult$iQuality);
                            
    imagedestroy($im);
                        }                
                    }
                }
            }
        }
        return 
    $sResult;

    I am even searching the directories via FTP and not seeing the thumbnail file, although I *am* seeing the renamed original file.

    Edit: Hmmm I just added the test part at the beginning of your script and added a "scaledown.png" file to that directory and it created the following:


    So maybe I'm just having problems with my part of the script and making sure that it includes the file and calls the function correctly.
    Last edited by d'Anconia; 05-30-2012 at 06:57 PM.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    That file path is invalid. Starting it with a / indicates it's moving from linux root (/). That should be without the /.
    Since it handles at the level of imagecreatefromstring, you can either use if/elseif/else, in array or switch multicase for this (since its all the same function call):
    PHP Code:
    switch ($imagetype)
    {
        case 
    IMAGETYPE_JPG:
        case 
    IMAGETYPE_PNG:
        case 
    IMAGETYPE_GIF:
            
    createThumbnail($random_logo_name'entities/images''_thumb' $new_width$new_height9true);
            break;


  • #11
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    The pathinfo() function was stating that it needs to have a string as its first argument but I can't do that since the file name will change every time.
    Also is there a reason you use only one "=" for testing conditionals? (Not that big of an issue, just curious).

    Since the script seems to work at the beginning when I create a "scaledown.png", this leads me to believe that somehow the inclusion of a folder path (since the original image files are in a sub-directory and the thumbnails will also be saved to a sub-directory) is creating a problem, either that or the way the function is called or switch statements are written is done incorrectly. It is still not creating a thumbnail in the entities/images folder.

    I have tried it with my original switch statement (from previous posts) as well as your switch statement but $imagetype is uninitialized and I don't know at what point I would initialize it nor what the code for initialization would look like. Here is my code (I just put the code of image_manipulation.php within the file_upload_script.php file since include() functions are just making it more complex than it needs to be while debugging:

    PHP Code:
    <?php # Based on script 10.3 - upload_image.php

    $sOriginal 'scaledown.gif';
    $aImageInfo getimagesize($sOriginal);
    $iNewWidth $aImageInfo[0] / 4;
    $iNewHeight $aImageInfo[1] / 4;

    if (
    $sCreated createThumbnail($sOriginal'.''tmb'$iNewWidth$iNewHeight))
    {
        
    printf('<div style="width: 300; height: 300; background-color: #555;"><img src="%s" alt="" /></div>'$sCreated);
    }

     function 
    findexts ($filename//Define findexts function
         

         
    $filename strtolower($filename) ; 
         global 
    $exts;
         
    $exts explode("."$filename) ; 
         
    $n count($exts)-1
         
    $exts $exts[$n]; 
         return 
    $exts
         } 

     function 
    createThumbnail($sImageName$sImagePath$suffix$newWidth$newHeight$iQuality 9$bPreserveAlpha true)
    {
        
    $sResult '';
        if (
    $im imagecreatetruecolor($newWidth$newHeight))
        {
            if (
    $bPreserveAlpha)
            {
                
    $trans imagecolortransparent($im);
                
    imagefill($im00$trans);
                
    imagealphablending($imtrue);
                
    imagesavealpha($imtrue);
            }
            
    $sPath realpath($sImagePath '/' $sImageName);
            if (
    is_file($sPath) && is_readable($sPath))
            {
                if (
    $fp fopen($sPath'rb'))
                {
                    
    $sBinary '';
                    while (
    $r fread($fp8192))
                    {
                        
    $sBinary .= $r;
                    }
                    
    fclose($fp);
                    if (
    $sPath imagecreatefromstring($sBinary))
                    {
                        if (
    imagecopyresampled($im$sPath0000$newWidth$newHeightimagesx($sPath), imagesy($sPath)))
                        {
                            
    $sResult pathinfo('entities/images/' $sImageNamePATHINFO_FILENAME) . $suffix '.png';
                            
    imagepng($im$sResult$iQuality);
                            
    imagedestroy($im);
                        }                
                    }
                }
            }
        }
        return 
    $sResult;
    }
        

    // Check if the form has been submitted:
    if (isset($_POST['submitted'])) {

        
    // Check for an uploaded file:
        
    if (isset($_FILES['upload'])) {
            
            
    // Validate the type. Should be JPEG or PNG.
            
    $allowed = array ('image/jpeg''image/JPG''image/PNG''image/png''image/GIF''image/gif');
            if (
    in_array($_FILES['upload']['type'], $allowed)) {
            
            
    findexts($_FILES['upload']['name']); // finds the extension of the uploaded file and returns $exts
            
    do 
                {
    //start do-while loop
                 //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. 
                 
    $ran rand (1999999999) ;
                
                 
    //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
                 
    $ran2 $ran '.';
                
                 
    //This assigns the subdirectory you want to save into... make sure it exists!
                             
                 
    $target "entities/images/";
                 
    //This combines the directory, the random file name, and the extension
                 
    $target $target $ran2 $exts
                 global 
    $random_logo_name;
                             global 
    $exts;
                 
    $random_logo_name $ran2 $exts;
                 
                 
    $random_filename_query "SELECT * FROM entities WHERE logo_path = '$random_logo_name'"
                 
    $rand_query_result mysqli_query ($dbc$random_filename_query);
                } while (
    mysqli_num_rows($rand_query_result) > ); //end do while loop
                            
                            
                // Move AND test if the file has been moved to permanent location
                
    if (move_uploaded_file ($_FILES['upload']['tmp_name'], "entities/images/" $random_logo_name)) {
                
    //    
                                
    list($image_width$image_height$image_type$attr)= getimagesize("entities/images/" $random_logo_name); 
                                if (
    $image_width >= $image_height) {
                                        
    $width_ratio $image_width 150;
                                        global 
    $new_height;
                                        global 
    $new_width;
                                        
    $new_height $image_height $width_ratio;
                                        
    $new_width $image_width $width_ratio;
                                   }
                                   else {
                                            
    $height_ratio $image_height 150;
                                            
    $new_width $image_width $height_ratio;
                                            
    $new_height $image_height $height_ratio;
                                   }
                               switch (
    $imagetype)
                                    {
                                        case 
    IMAGETYPE_JPG:
                                        case 
    IMAGETYPE_PNG:
                                        case 
    IMAGETYPE_GIF:
                                            
    createThumbnail($random_logo_name'entities/images''_thumb' $new_width$new_height9true);
                                            break;
                                    }
                                   
                                
                  echo 
    '<p><em>The file has been uploaded!</em></p>';
                } 
    // End of move... IF.
                
    else { echo '<p><em>The file has not been uploaded correctly</em></p>';}
                
            } else { 
    // Invalid type.
                
    echo '<p class="error">Please upload a JPEG, GIF, or PNG image.</p>';
            }

        } 
    // End of isset($_FILES['upload']) IF.
        
        // Check for an error:
        
        
    if ($_FILES['upload']['error'] > 0) {
            echo 
    '<p class="error">The file could not be uploaded because: <strong>';
        
            
    // Print a message based upon the error.
            
    switch ($_FILES['upload']['error']) {
                case 
    1:
                    print 
    'The file exceeds the upload_max_filesize setting in php.ini.';
                    break;
                case 
    2:
                    print 
    'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                    break;
                case 
    3:
                    print 
    'The file was only partially uploaded.';
                    break;
                case 
    4:
                    print 
    'No file was uploaded.';
                    break;
                case 
    6:
                    print 
    'No temporary folder was available.';
                    break;
                case 
    7:
                    print 
    'Unable to write to the disk.';
                    break;
                case 
    8:
                    print 
    'File upload stopped.';
                    break;
                default:
                    print 
    'A system error occurred.';
                    break;
            } 
    // End of switch.
            
            
    print '</strong></p>';
            
        } 
    // End of error IF.
        
        // Delete the file if it still exists:
        
    if (file_exists ($_FILES['upload']['name']) && is_file($_FILES['upload']['name']) ) {
            
    unlink ($_FILES['upload']['name']);
        }
                
    // End of the submitted conditional.
    ?>
    At this point I wish I had a contracted coder who could take care of these sorts of issues.
    Last edited by d'Anconia; 05-31-2012 at 10:13 AM.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #12
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Sorry, you need to switch on $image_path, not $imagePath.
    I can't test this where I am, so you'll need to post back if that solves it. Until the switch is valid, no call to the createThumbnail is made, and without that it won't create one.

    I noticed a number of global calls here. You are already in global scope so its not necessary to call global anywhere within the main. Functions like findexts shouldn't be invoking global either, you should be creating and returning the result and assigning that at call time instead of relying on it creating the $exts for you. Global is a debugging nightmare so it should only be used where you cannot modify a function signature, which would be only a function pointer in a callback method like usort, set_error_handler, etc.

  • Users who have thanked Fou-Lu for this post:

    d'Anconia (06-01-2012)

  • #13
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Okay I'll post back in a couple of hours when I can test it a little (at work right now).
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #14
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Well I've got some very good news. I have gotten the script to work.

    The first (and largest) error I happened to make was that when I changed the modified files I forgot to change the "Submit" button script to the modified files. This explains why your scaledown.png file was having its thumbnail made but not the image I was submitting (note that this was when I was accessing the script directly by writing in the URL in the search bar).

    The code still seemed to have issues with your switch function so I went back to my earlier switch function and it worked. I think perhaps the issue it had with your switch function had to do with the fact that it was testing a file name but I also had to include the directory name before it since that file was not in the same folder as the script. I could be wrong though as I'm not as familiar with the IMAGE_TYPE function (it also seems that the jpg image type should actually be jpeg.

    Was also having issues with $sResult being returned correctly but as it turns out the variable just needed to be initialized at the very beginning of the script (I believe this is a low level error anyway only visible when site is not 'live').

    Thanks a ton for the help Fou Lu, I couldn't have done it without you and I am sorry that part of the issue was an omitted mistake by me. For the record my final code is below:


    PHP Code:
    <?php # Based on script 10.3 - upload_image.php

    /*$sOriginal = 'scaledown3.gif';
    $aImageInfo = getimagesize($sOriginal);
    $iNewWidth = $aImageInfo[0] / 4;
    $iNewHeight = $aImageInfo[1] / 4;

    if ($sCreated = createThumbnail($sOriginal, '.', 'tmb', $iNewWidth, $iNewHeight))
    {
        printf('<div style="width: 300; height: 300; background-color: #555;"><img src="%s" alt="" /></div>', $sCreated);
    }
    */
     
    function findexts ($filename//Define findexts function
         

         
    $filename strtolower($filename) ; 
         
    $exts explode("."$filename) ; 
         
    $n count($exts)-1
         
    $exts $exts[$n]; 
         return 
    $exts
         } 

     function 
    createThumbnail($sImageName$sImagePath$suffix$newWidth$newHeight$iQuality 9$bPreserveAlpha true)
    {
        
    $sResult '';
        if (
    $im imagecreatetruecolor($newWidth$newHeight))
        {
            if (
    $bPreserveAlpha)
            {
                echo 
    'preserve alpha set';
                
    $trans imagecolortransparent($im);
                
    imagefill($im00$trans);
                
    imagealphablending($imtrue);
                
    imagesavealpha($imtrue);
            }
            
    $sPath realpath($sImagePath '/' $sImageName);
            if (
    is_file($sPath) && is_readable($sPath))
            {   
                echo 
    'spath is file and readable';
                if (
    $fp fopen($sPath'rb'))
                {
                    echo 
    'spath is opened and "rb"';
                    
    $sBinary '';
                    while (
    $r fread($fp8192))
                    {
                        
    $sBinary .= $r;
                    }
                    
    fclose($fp);
                    if (
    $sPath imagecreatefromstring($sBinary))
                    {   
                        echo 
    'image is created from string (binary) and set to sPath';
                        if (
    imagecopyresampled($im$sPath0000$newWidth$newHeightimagesx($sPath), imagesy($sPath)))
                        {   
                            echo 
    'image copy resampled';
                            
    $sResult pathinfo($sImageNamePATHINFO_FILENAME) . $suffix '.png';
                            
    imagepng($im'entities/images/' $sResult$iQuality);
                            
    imagedestroy($im);
                        }                
                    }
                }
            }
        }
        return 
    $sResult;
    }
        

    // Check if the form has been submitted:
    if (isset($_POST['submitted'])) {

        
    // Check for an uploaded file:
        
    if (isset($_FILES['upload'])) {
            
            
    // Validate the type. Should be JPEG or PNG.
            
    $allowed = array ('image/jpeg''image/JPG''image/PNG''image/png''image/GIF''image/gif');
            if (
    in_array($_FILES['upload']['type'], $allowed)) {
            
            
    $exts findexts($_FILES['upload']['name']); // finds the extension of the uploaded file and returns $exts
            
    do 
                {
    //start do-while loop
                 //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. 
                 
    $ran rand (1999999999) ;
                
                 
    //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
                 
    $ran2 $ran '.';
                
                 
    //This assigns the subdirectory you want to save into... make sure it exists!
                             
                 
    $target "entities/images/";
                 
    //This combines the directory, the random file name, and the extension
                 
    $target $target $ran2 $exts
                 
    $random_logo_name $ran2 $exts;
                 
                 
    $random_filename_query "SELECT * FROM entities WHERE logo_path = '$random_logo_name'"
                 
    $rand_query_result mysqli_query ($dbc$random_filename_query);
                } while (
    mysqli_num_rows($rand_query_result) > ); //end do while loop
                            
                            
                // Move AND test if the file has been moved to permanent location
                
    if (move_uploaded_file ($_FILES['upload']['tmp_name'], "entities/images/" $random_logo_name)) {
                
    //    
                                
    list($image_width$image_height$image_type$attr)= getimagesize("entities/images/" $random_logo_name); 
                                if (
    $image_width >= $image_height) {
                                        
    $width_ratio $image_width 150;
                                        
    $new_height $image_height $width_ratio;
                                        
    $new_width $image_width $width_ratio;
                                   }
                                   else {
                                            
    $height_ratio $image_height 150;
                                            
    $new_width $image_width $height_ratio;
                                            
    $new_height $image_height $height_ratio;
                                   }
                               switch (
    $exts) {
                                    case 
    'jpeg':
                                        
    createThumbnail($random_logo_name'entities/images''_thumb' $new_width$new_height9true); 
                                        break;
                                    case 
    'jpg':
                                        
    createThumbnail($random_logo_name'entities/images''_thumb' $new_width$new_height9true); 
                                        break;
                                    case 
    'gif':
                                        
    createThumbnail($random_logo_name'entities/images''_thumb' $new_width$new_height9true);
                                        break;
                                    case 
    'png':
                                        
    createThumbnail($random_logo_name'entities/images''_thumb' $new_width$new_height9true);
                                        break;
                                }
                                   
                                
                  echo 
    '<p><em>The file has been uploaded!</em></p>';
                } 
    // End of move... IF.
                
    else { echo '<p><em>The file has not been uploaded correctly</em></p>';}
                
            } else { 
    // Invalid type.
                
    echo '<p class="error">Please upload a JPEG, GIF, or PNG image.</p>';
            }

        } 
    // End of isset($_FILES['upload']) IF.
        
        // Check for an error:
        
        
    if ($_FILES['upload']['error'] > 0) {
            echo 
    '<p class="error">The file could not be uploaded because: <strong>';
        
            
    // Print a message based upon the error.
            
    switch ($_FILES['upload']['error']) {
                case 
    1:
                    print 
    'The file exceeds the upload_max_filesize setting in php.ini.';
                    break;
                case 
    2:
                    print 
    'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                    break;
                case 
    3:
                    print 
    'The file was only partially uploaded.';
                    break;
                case 
    4:
                    print 
    'No file was uploaded.';
                    break;
                case 
    6:
                    print 
    'No temporary folder was available.';
                    break;
                case 
    7:
                    print 
    'Unable to write to the disk.';
                    break;
                case 
    8:
                    print 
    'File upload stopped.';
                    break;
                default:
                    print 
    'A system error occurred.';
                    break;
            } 
    // End of switch.
            
            
    print '</strong></p>';
            
        } 
    // End of error IF.
        
        // Delete the file if it still exists:
        
    if (file_exists ($_FILES['upload']['name']) && is_file($_FILES['upload']['name']) ) {
            
    unlink ($_FILES['upload']['name']);
        }
                
    // End of the submitted conditional.
    ?>
    Isn't it beautiful?!
    Last edited by d'Anconia; 05-31-2012 at 09:44 PM.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •