Search code examples
php-gdpligg

Replacing "imagecopyresized" function with "imagecopyresampled" in image upload module


I'm currently working on Pligg CMS-based website and its default Image Upload Module which attaches thumbnails to posts from user provided links is using PHP's GD library for image processing. The thumbnails resulted have a reduced quality and after a little bit of web search I found that I should replace the imagecopyresized function with imagecopyresampled.

The main problem is I am a rookie in web development and I don't know where to start. The chunk of code I think (thus maybe wrong) is responsible for the image processing and needs to be edited is the following:

// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image 
while (file_exists("$thumb_dir/$name$i.jpg")) $i++;
$name = "$name$i.jpg";

imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

if (!imagejpeg( $tmp_img, "$thumb_dir/$name",$settings['quality'] ))
    $error .= "Can't create thumbnail $thumb_dir/$name";
else
    $db->query("INSERT INTO ".table_prefix."files 
            SET file_size='$size',
                file_orig_id='$orig_id',
                file_user_id={$current_user->user_id},
                file_link_id=$link_id,
                file_ispicture=1,
                file_comment_id='".$db->escape($_POST['comment'])."',
                file_real_size='".filesize("$thumb_dir/$name")."',
                file_name='".$db->escape($name)."'");
}
return $error;

From what I see, the image is first processed through the imagecreatruecolor function into a new tmp_img which is then processed through the imagecopyresized function.

Since I don't have experience, I can't tell if this is the right path for an image of XY size to be resized without reducing its quality. Should I replace both imagecreatetruecolor and imagecopyresized with imagecopyresampled?


Solution

  • imagecopyresized and imagecopyresampled have identical parameter requirements so you can simply change the function name in the following line:

    imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    

    Everything else should stay the same.

    Note that your code is vulnerable to SQL Injection. Read up on, and start using, prepared statements.