如何在imagecreatefromjpeg函数中使用之前调整上传图像的大小?

I have a code that allows file upload and some text input. It uses the uploaded file in an imagacreatefromjepg and imagecopymerge. I want to resize the uploaded file to a definite size which is 255x175. how can i make it? Here is what is have:

        $now = time();
    while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
    {
        $now++;
    }

    // now let's move the file to its final and allocate it with the new filename
    @move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
        or error('receiving directory insuffiecient permission', $uploadForm);

    $upload = $uploadFilename;
    $im = imagecreatefromjpeg("bg.jpg");
    $img2 = imagecreatefromjpeg($upload);
    $black = imagecolorallocate($im, 0, 0, 0);
    $font = 'arialbi.ttf';
    $font2 = 'ariali.ttf';

    imagettftext($im, 24, 0, 50, 280, $black, $font, $title);
    imagettftext($im, 10, 0, 320, 362, $black, $font, $namehere);

    imagecopymerge($im, $img2, 30, 350, 0, 0, imagesx($img2), imagesy($img2), 100);

    $date_created = date("YmdHis");//get date created
    $img_name = "-img_entry.jpg"; //the file name of the generated image
    $img_newname = $date_created . $img_name; //datecreated+name
    $img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save the image 
    imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality

    $newpath = "/home3/site/public_html/mainfolder/image_entry/";//path to another folder
    $newdir = $newpath.$img_newname;
    copy ($img_dir, $newdir); //copy to new folder

    imagedestroy($im);

Hope you can help me fix this. I have raed the posts Resize image before uploading PHP and Php resize width fix. But I dont know how to apply it in my case. Thanks for any and all help.

just after: imagecopymerge($im,... line

$mini_width = ...;// calculate desirable width
$mini_height = ...;// calculate desirable height
$mini_img = @ImageCreateTrueColor($mini_width, $mini_height);
imagecopyresampled($mini_img, $img2, 0, 0, 0, 0, $mini_width, $mini_height, imagesx($img2), imagesy($img2));

next line is $date_created = date(...

change imagejpeg($im, $img_dir , 80); to:

imagejpeg($mini_img, $img_dir , 80);

and finally change imagedestroy($im); to imagedestroy($mini_img);

Actually, you can, but not have to call imagedestroy() for all the resource images created above.