Where is the quality gone... image upload

Discussion in 'PHP' started by oo7ml, Jun 3, 2010.

  1. #1
    Hi,

    I have used the upload image script below on several sites but now some clients are reporting that their images are loosing a lot of quality when they are uploaded... can anyone see why or suggest anything that i could do to stop the images from loosing quality... thanks in advance

    <?php
    
    $default_width = 600;
    $default_height = 450;
    
    $thumbnails = true;
    $thumb_width = 100;
    $thumb_height = 75;
    
    $bg_color = "#777777";
    $directory = "images/";
    
    //define a maxim size for the uploaded images in Kb
    define ("MAX_SIZE","100000");
    
    //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
    function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    }
    
    
    
    //This variable is used as a flag. The value is initialized with 0 (meaning no error found)
    //and it will be changed to 1 if an error occures.
    //If the error occures the file will not be uploaded.
    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['Submit']))
    {
        //reads the name of the file the user submitted for uploading
        $image=$_FILES['image']['name'];
        $file_tmp = $_FILES['image']['tmp_name'];
        $file_type = $_FILES['image']['type'];
        //if it is not empty
        if ($image)
        {
            //get the original name of the file from the clients machine
            $filename = stripslashes($_FILES['image']['name']);
            //get the extension of the file in a lower case format
            $extension = strtolower(getExtension($filename));
            //if it is not a known extension, we will suppose it is an error and will not upload the file,
            //otherwise we will do more tests
            if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
            {
                //print error message
                echo '<h1>Unknown extension!</h1>';
                $errors=1;
            }
            else
            {
                //get the size of the image in bytes
                //$_FILES['image']['tmp_name'] is the temporary filename of the file
                //in which the uploaded file was stored on the server
                $size=filesize($_FILES['image']['tmp_name']);
                //compare the size with the maxim size we defined and print error if bigger
                if ($size > MAX_SIZE*1024)
                {
                    echo '<h1>You have exceeded the size limit!</h1>';
                    $errors=1;
                }
                
                //we will give an unique name, for example the time in unix time format
                $filename = time();
                $image_name = $directory.$filename.'.'.$extension;
                $thumb_name = $directory.$filename.'_s.'.$extension;
                        
                list($width, $height) = getimagesize($file_tmp);
    
                if($width>$default_width && $height>$default_height)
                {
                    //calculate X and Y scale, and default x/y ratio
                    $xscale = $width/$default_width;
                    $yscale = $height/$default_height;
                    $default_ratio = $default_width/$default_height;
                    if($xscale > $yscale)
                    {
                        $final_height = $default_height;
                        $final_width = $width/$yscale;
                        $crop_x = ($default_width - $final_width)/2;
                        $crop_y = 0;
                    } else {
                        $final_width = $default_width;
                        $final_height = $height/$xscale;
                        $crop_x = 0;
                        $crop_y = ($default_height - $final_height)/2;                                          
                    }
                    
                } else {
                    $crop_x = ($default_width - $width)/2;
                    $crop_y = ($default_height - $height)/2;
                    $final_width = $width;
                    $final_height = $height;
                  
                }
                
                //create image
                $imageResized = imagecreatetruecolor($default_width, $default_height);
    
                
                
                
                //create background color
                $red = 100;
                $green = 100;
                $blue = 100;
                //convert from HTML color to RGB
                if( eregi( "[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $bg_color, $ret ) )
                {
                    $red = hexdec( $ret[1] );
                    $green = hexdec( $ret[2] );
                    $blue = hexdec( $ret[3] );
                }
                $fill_color = ImageColorAllocate( $imageResized, $red, $green, $blue ); 
                imagefill($imageResized, 0, 0, $fill_color);
                	      
                if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
                    $imageTmp = imagecreatefromjpeg($file_tmp);
                }elseif($file_type == "image/x-png" || $file_type == "image/png"){
                    $imageTmp = imagecreatefrompng($file_tmp);
                }elseif($file_type == "image/gif"){
                    $imageTmp = imagecreatefromgif($file_tmp);
                }
                
                imagecopyresampled($imageResized, $imageTmp, $crop_x, $crop_y, 0, 0, $final_width, $final_height, $width, $height);
                
    
                
                //finally, save the image
                imagejpeg($imageResized, $image_name);
                        
    			//create thumbnails
                if($thumbnails==true){
                    $imageThumb   = imagecreatetruecolor($thumb_width, $thumb_height);
                    imagecopyresampled($imageThumb, $imageResized, 0, 0, 0, 0, $thumb_width, $thumb_height, $default_width, $default_height);
                    imagejpeg($imageThumb, $thumb_name);
                    ImageDestroy ($imageThumb);
                }
                
                ImageDestroy ($imageResized); 
                ImageDestroy ($imageTmp);  
            }
        }
    }
    
    //If no errors registred, print the success message
    if(isset($_POST['Submit']) && !$errors)
    {
        echo "<h1>File Uploaded Successfully!</h1>";
        echo '<a href="'.$image_name.'"><img src="'.$thumb_name.'"></a>';
    }
    
    ?>
    
    <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
    <form name="newad" method="post" enctype="multipart/form-data" action="">
    <table>
    <tr><td><input type="file" name="image"></td></tr>
    <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
    </table>
    </form>
    PHP:
     
    oo7ml, Jun 3, 2010 IP
  2. flexdex

    flexdex Peon

    Messages:
    104
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try a higher quality, default is 75

    bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )
     
    flexdex, Jun 3, 2010 IP
  3. oo7ml

    oo7ml Well-Known Member

    Messages:
    656
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    105
    #3
    Ok cool, thanks, so should i just set the quality to 100
     
    oo7ml, Jun 3, 2010 IP
  4. Scripts man

    Scripts man Guest

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Scripts man, Jun 3, 2010 IP
  5. flexdex

    flexdex Peon

    Messages:
    104
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    You could additionally improve the quality of JPEG images if you use adaptive resizing in some cases (but not for thumbnails) instead of resampling. That could let images look less blurry.
     
    flexdex, Jun 3, 2010 IP