Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I optimize this function?
    primarykey
    data
    text
    <p>I created a function for generating and saving multiple image sizes when a user uploads an image via a web form. I was wondering, how can I better optimize my code (reduce the number of lines while still being easily readable)</p> <p><code>save_image($_FILES['image'], $_GET['member_id'], 250, 300, large) //usage example</code> </p> <p>The Function</p> <pre><code>function save_image($file, $id, $sizex, $sizey, $pre){ $image=$_FILES['image']['name']; $tmpName = $_FILES['image']['tmp_name']; 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 = getExtension($filename); $extension = strtolower($extension); if (($extension == "jpg") || ($extension == "jpeg")){ $size = getimagesize($tmpName); $max_x = 180; $max_y = 300; $img = imagecreatefromjpeg($file['tmp_name']); $imagex = imagesx($img); $imagey = imagesy($img); $dim = max($imagex/$max_x, $imagey/$max_y); $nx = $imagex/$dim; $ny = $imagey/$dim; $image = imagecreatetruecolor($nx, $ny); imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey); imagejpeg($image, '../images/uploads/'.$id.'-large.jpg'); //Make the thumb $size = getimagesize($tmpName); $max_x = 120; $max_y = 230; $img = imagecreatefromjpeg($file['tmp_name']); $imagex = imagesx($img); $imagey = imagesy($img); $dim = max($imagex/$max_x, $imagey/$max_y); $nx = $imagex/$dim; $ny = $imagey/$dim; $image = imagecreatetruecolor($nx, $ny); imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey); imagejpeg($image, '../images/uploads/'.$id.'-med.jpg'); $size = getimagesize($tmpName); $max_x = 60; $max_y = 115; $img = imagecreatefromjpeg($file['tmp_name']); $imagex = imagesx($img); $imagey = imagesy($img); $dim = max($imagex/$max_x, $imagey/$max_y); $nx = $imagex/$dim; $ny = $imagey/$dim; $image = imagecreatetruecolor($nx, $ny); imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey); imagejpeg($image, '../images/uploads/'.$id.'-thumb.jpg'); }else{ return false; } }else{ return false; } return true; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload