Jump to content

image resize


runnerjp

Recommended Posts

i belive this code would resize my images to 600 each way

 

$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

 

what im having trouble is inserting it into here

 

<?php
  }else{
    /**
     * PROCESS FORM
     */

    // %% debugging info
    dbg_out($_SESSION);
    dbg_out($_FILES);
    
    // First line of error checking, make sure upload successful
    if($_FILES['image']['error'] !== UPLOAD_ERR_OK){
      echo 'Error: There was an error with your upload.';
      exit();
    }

    // Now we know we have an uploaded file, let's check the type
    $image_size = getimagesize($_FILES['image']['tmp_name']);
    if($image_size === FALSE){
      echo 'Error: getimagesize() has failed.';
      exit();
    }

    // Debug print the mime type that was found
    dbg_out($image_size['mime']);
    $img_arr = explode('/', $image_size['mime']);
    if(count($img_arr) != 2){
      echo 'Error: Problem with image type';
      exit();
    }
    $type = $img_arr[0];         // mime type
    $ext = $img_arr[1];          // file extension
    if(strlen($type) == 0 || strlen($ext) == 0){
      // Neither of those vars can be zero length
      echo 'Error: No type or extension found';
      exit();
    }
    if($type != 'image'){
      // Not an image!
      echo 'Error: Uploaded file was not an image';
      exit();
    }

    //get users ID
    $id = $_SESSION['user_id'];

    //don't continue if an image hasn't been uploaded
    if(is_uploaded_file($_FILES['image']['tmp_name'])){
        // set destination directory
        $dst = realpath(dirname(__FILE__) . '/images') . '/' . $id
       	     . '.' . $ext;
        dbg_out($dst); // %%
        if(move_uploaded_file($_FILES['image']['tmp_name'], $dst)){
          // Success, file has been moved and renamed
          // now do whatever else is necessary
          dbg_out('SUCCESS!'); // %%
          $Clean = Array();
          $Clean['user_id'] = "'"
                            . mysql_real_escape_string($id) 
                            . "'";
          $Clean['ext'] = "'" 
                        . mysql_real_escape_string($ext) 
                        . "'";
$sql = "DELETE FROM `user_images` WHERE `user_id`={$Clean['user_id']}";
          $q = mysql_query($sql);
          if($q === FALSE){
            dbg_out('ERROR: ' . mysql_error());
          }else{
            dbg_out('Database delete successful');
          }
          $sql = "
            INSERT INTO `user_images` 
              (`user_id`, `ext`, `created`, `modified`)
            VALUES (
              {$Clean['user_id']}, {$Clean['ext']}, NOW(), NOW()
            )
          ";
          $q = mysql_query($sql);
          if($q === FALSE){
            dbg_out('ERROR: ' . mysql_error());
          }else{
            dbg_out('Database insert successful');
          }          }
        }
      }?>

 

tried everything and really stuck

Link to comment
Share on other sites

no script can upload images fine... im trying to resize them all so when upload it resizes them the 600x 600

 

e.g

$newwidth=600;

$newheight=($height/$width)*600;

$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

 

but i need to insert it into my original script but i can figure out how

Link to comment
Share on other sites

i tried

<?php
  }else{
    /**
     * PROCESS FORM
     */

    // %% debugging info
    dbg_out($_SESSION);
    dbg_out($_FILES);
      // Input
    $s_image = $_GET['image']; // Image url set in the URL. ex: thumbit.php?image=URL
    $e_image = "error.jpg"; // If there is a problem using the file extension then load an error JPG.
    $max_width = 100; // Max thumbnail width.
    $max_height = 250; // Max thumbnail height.
       $quality = 100; // Do not change this if you plan on using PNG images.

    // Resizing and Output : Do not edit below this line unless you know what your doing.

    if (preg_match("/.jpg/i", "$s_image"))  {

    header('Content-type: image/jpeg');
      list($width, $height) = getimagesize($s_image);
    $ratio = ($width > $height) ? $max_width/$width : $max_height/$height; 
    if($width > $max_width || $height > $max_height) { 
    $new_width = $width * $ratio; 
    $new_height = $height * $ratio; 
    } else {
    $new_width = $width; 
    $new_height = $height;
    } 
      $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($s_image); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagejpeg($image_p, null, $quality); 
    imagedestroy($image_p); 

    }
       elseif (preg_match("/.png/i", "$s_image"))  {

    header('Content-type: image/png');
      list($width, $height) = getimagesize($s_image);
    $ratio = ($width > $height) ? $max_width/$width : $max_height/$height; 
    if($width > $max_width || $height > $max_height) { 
    $new_width = $width * $ratio; 
    $new_height = $height * $ratio; 
    } else {
    $new_width = $width; 
    $new_height = $height;
    } 
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefrompng($s_image); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagepng($image_p, null, $quality); 
    imagedestroy($image_p); 

    }
       elseif (preg_match("/.gif/i", "$s_image"))  {

    header('Content-type: image/gif');
      list($width, $height) = getimagesize($s_image);
    $ratio = ($width > $height) ? $max_width/$width : $max_height/$height; 
    if($width > $max_width || $height > $max_height) { 
    $new_width = $width * $ratio; 
    $new_height = $height * $ratio; 
    } else {
    $new_width = $width; 
    $new_height = $height;
    } 
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromgif($s_image); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagegif($image_p, null, $quality);
    imagedestroy($image_p); 

    }
       else {

    // Show the error JPG.
    header('Content-type: image/jpeg');
    imagejpeg($e_image, null, $quality); 
    imagedestroy($e_image); 

    } 
    
    // First line of error checking, make sure upload successful
    if($_FILES['image']['error'] !== UPLOAD_ERR_OK){
      echo 'Error: There was an error with your upload.';
      exit();
    }

    // Now we know we have an uploaded file, let's check the type
    $image_size = getimagesize($_FILES['image']['tmp_name']);
    if($image_size === FALSE){
      echo 'Error: getimagesize() has failed.';
      exit();
    }

    // Debug print the mime type that was found
    dbg_out($image_size['mime']);
    $img_arr = explode('/', $image_size['mime']);
    if(count($img_arr) != 2){
      echo 'Error: Problem with image type';
      exit();
    }
    $type = $img_arr[0];         // mime type
    $ext = $img_arr[1];          // file extension
    if(strlen($type) == 0 || strlen($ext) == 0){
      // Neither of those vars can be zero length
      echo 'Error: No type or extension found';
      exit();
    }
    if($type != 'image'){
      // Not an image!
      echo 'Error: Uploaded file was not an image';
      exit();
    }

    //get users ID
    $id = $_SESSION['user_id'];

    //don't continue if an image hasn't been uploaded
    if(is_uploaded_file($_FILES['image']['tmp_name'])){
        // set destination directory
        $dst = realpath(dirname(__FILE__) . '/images') . '/' . $id
                . '.' . $ext;
        dbg_out($dst); // %%
        if(move_uploaded_file($_FILES['image']['tmp_name'], $dst)){
          // Success, file has been moved and renamed
          // now do whatever else is necessary
          dbg_out('SUCCESS!'); // %%
          $Clean = Array();
          $Clean['user_id'] = "'"
                            . mysql_real_escape_string($id) 
                            . "'";
          $Clean['ext'] = "'" 
                        . mysql_real_escape_string($ext) 
                        . "'";
$sql = "DELETE FROM `user_images` WHERE `user_id`={$Clean['user_id']}";
          $q = mysql_query($sql);
          if($q === FALSE){
            dbg_out('ERROR: ' . mysql_error());
          }else{
            dbg_out('Database delete successful');
          }
          $sql = "
            INSERT INTO `user_images` 
              (`user_id`, `ext`, `created`, `modified`)
            VALUES (
              {$Clean['user_id']}, {$Clean['ext']}, NOW(), NOW()
            )
          ";
          $q = mysql_query($sql);
          if($q === FALSE){
            dbg_out('ERROR: ' . mysql_error());
          }else{
            dbg_out('Database insert successful');
          }          }
        }
      }
    /* Everything else you had is irrelevant at this point */
  

  /**
   * remove this function later and all calls to it
   */
  function dbg_out($msg){
    if(is_bool($msg)){
      $msg = $msg ? '[TRUE]' : '[FALSE]';
    }else if(is_null($msg)){
      $msg = '[NULL]';
    }else if(is_string($msg) && strlen($msg) == 0){
      $msg = '[EMPTY STRING]';
    }
    echo '<pre style="text-align: left;">'
       . print_r($msg, true)
       . '</pre>';
  }


?>

 

but getting

Warning: Cannot modify header information - headers already sent by (output started at /home/runningp/public_html/members/upload.php:192) in /home/runningp/public_html/members/upload.php on line 95

 

Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/runningp/public_html/members/upload.php on line 96

 

Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/runningp/public_html/members/upload.php on line 97

as my errors

Link to comment
Share on other sites

ok got code working

<?php
    if(isset($_POST['uploaded'])){
    /**
     * PROCESS FORM
     */

    // %% debugging info
    dbg_out($_SESSION);
    dbg_out($_FILES);
      // Input
    $s_image = $_GET['image']; // Image url set in the URL. ex: thumbit.php?image=URL
    $e_image = "error.jpg"; // If there is a problem using the file extension then load an error JPG.
    $max_width = 100; // Max thumbnail width.
    $max_height = 250; // Max thumbnail height.
       $quality = 100; // Do not change this if you plan on using PNG images.

    // Resizing and Output : Do not edit below this line unless you know what your doing.

    if (preg_match("/.jpg/i", "$s_image"))  {

    header('Content-type: image/jpeg');
      list($width, $height) = getimagesize($s_image);
    $ratio = ($width > $height) ? $max_width/$width : $max_height/$height; 
    if($width > $max_width || $height > $max_height) { 
    $new_width = $width * $ratio; 
    $new_height = $height * $ratio; 
    } else {
    $new_width = $width; 
    $new_height = $height;
    } 
      $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($s_image); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagejpeg($image_p, null, $quality); 
    imagedestroy($image_p); 

    }
       elseif (preg_match("/.png/i", "$s_image"))  {

    header('Content-type: image/png');
      list($width, $height) = getimagesize($s_image);
    $ratio = ($width > $height) ? $max_width/$width : $max_height/$height; 
    if($width > $max_width || $height > $max_height) { 
    $new_width = $width * $ratio; 
    $new_height = $height * $ratio; 
    } else {
    $new_width = $width; 
    $new_height = $height;
    } 
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefrompng($s_image); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagepng($image_p, null, $quality); 
    imagedestroy($image_p); 

    }
       elseif (preg_match("/.gif/i", "$s_image"))  {

    header('Content-type: image/gif');
      list($width, $height) = getimagesize($s_image);
    $ratio = ($width > $height) ? $max_width/$width : $max_height/$height; 
    if($width > $max_width || $height > $max_height) { 
    $new_width = $width * $ratio; 
    $new_height = $height * $ratio; 
    } else {
    $new_width = $width; 
    $new_height = $height;
    } 
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromgif($s_image); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagegif($image_p, null, $quality);
    imagedestroy($image_p); 

    }
       else {

    // Show the error JPG.
    header('Content-type: image/jpeg');
    imagejpeg($e_image, null, $quality); 
    imagedestroy($e_image); 

    } 
    
    // First line of error checking, make sure upload successful
    if($_FILES['image']['error'] !== UPLOAD_ERR_OK){
      echo 'Error: There was an error with your upload.';
      exit();
    }

    // Now we know we have an uploaded file, let's check the type
    $image_size = getimagesize($_FILES['image']['tmp_name']);
    if($image_size === FALSE){
      echo 'Error: getimagesize() has failed.';
      exit();
    }

    // Debug print the mime type that was found
    dbg_out($image_size['mime']);
    $img_arr = explode('/', $image_size['mime']);
    if(count($img_arr) != 2){
      echo 'Error: Problem with image type';
      exit();
    }
    $type = $img_arr[0];         // mime type
    $ext = $img_arr[1];          // file extension
    if(strlen($type) == 0 || strlen($ext) == 0){
      // Neither of those vars can be zero length
      echo 'Error: No type or extension found';
      exit();
    }
    if($type != 'image'){
      // Not an image!
      echo 'Error: Uploaded file was not an image';
      exit();
    }

    //get users ID
    $id = $_SESSION['user_id'];

    //don't continue if an image hasn't been uploaded
    if(is_uploaded_file($_FILES['image']['tmp_name'])){
        // set destination directory
        $dst = realpath(dirname(__FILE__) . '/images') . '/' . $id
                . '.' . $ext;
        dbg_out($dst); // %%
        if(move_uploaded_file($_FILES['image']['tmp_name'], $dst)){
          // Success, file has been moved and renamed
          // now do whatever else is necessary
          dbg_out('SUCCESS!'); // %%
          $Clean = Array();
          $Clean['user_id'] = "'"
                            . mysql_real_escape_string($id) 
                            . "'";
          $Clean['ext'] = "'" 
                        . mysql_real_escape_string($ext) 
                        . "'";
$sql = "DELETE FROM `user_images` WHERE `user_id`={$Clean['user_id']}";
          $q = mysql_query($sql);
          if($q === FALSE){
            dbg_out('ERROR: ' . mysql_error());
          }else{
            dbg_out('Database delete successful');
          }
          $sql = "
            INSERT INTO `user_images` 
              (`user_id`, `ext`, `created`, `modified`)
            VALUES (
              {$Clean['user_id']}, {$Clean['ext']}, NOW(), NOW()
            )
          ";
          $q = mysql_query($sql);
          if($q === FALSE){
            dbg_out('ERROR: ' . mysql_error());
          }else{
            dbg_out('Database insert successful');
          }          }
        }
      }
    /* Everything else you had is irrelevant at this point */
  

  /**
   * remove this function later and all calls to it
   */
  function dbg_out($msg){
    if(is_bool($msg)){
      $msg = $msg ? '[TRUE]' : '[FALSE]';
    }else if(is_null($msg)){
      $msg = '[NULL]';
    }else if(is_string($msg) && strlen($msg) == 0){
      $msg = '[EMPTY STRING]';
    }
    echo '<pre style="text-align: left;">'
       . print_r($msg, true)
       . '</pre>';
  }

  session_start();
  require_once '../settings.php';

    /**
     * DISPLAY FORM
     */
?>
    <form action="" method="post" enctype="multipart/form-data">
      Upload:<br><br>
      <input type="file" name="image"><br><br>
      <input type="hidden" name="uploaded" value="1">
      <input type="submit" value="Upload">
    </form>

 

but it fails to resize the image..how comes :

Link to comment
Share on other sites

@runnerjp

 

I don't have any experience resizing images with the built-in PHP functions; I use a utility named convert on my linux host.

 

The best way to go about tackling new programming problems is to separate all other complexities from the problem at hand.  Currently, your problem pertains to resizing an image and you are trying to solve it in an existing script.  The danger in this approach is when it's not working, it's sometimes unclear if the problem lies in your image resizing code or somewhere else in the script.

 

Create a separate test folder on your host, FTP a couple of images there, and use some tutorials from the PHP manual (or elsewhere on the 'net) to write a script that does one thing and one thing only:  resizes an image that is already present in the directory.

 

Work it through, be methodical, and think about your errors as you get them.  When it's working apply it to your existing script.

 

I know that's not the answer you were looking for, but it's the best way to learn.

Link to comment
Share on other sites

seeing as we are talking about this, i am using osc and just ran a mod

 


  //start
        $filename = $this->destination . $this->filename;
        $maxHeight = 498;
        $maxWidth = 664;

        $extension = substr($filename,-3);
        if($extension == 'gif')
        {
            $src = imagecreatefromgif($filename);
        }
        elseif($extension == 'png')
        {
            $src = imagecreatefrompng($filename);
        }
        elseif($extension == 'jpg'||$extension == 'jpeg')
        {
        $src = imagecreatefromjpeg($filename);

        }

        $oldWidth = imagesx($src);
        $oldHeight = imagesy($src);

        if($oldWidth > $maxWidth||$oldHeight > $maxHeight)
        {
            if(($maxWidth/$oldWidth) >= ($maxHeight/$oldHeight))
                $factor = $maxHeight/$oldHeight;
            else
                                $factor = $maxWidth/$oldWidth;
                                $newWidth = $oldWidth*$factor;
                                $newHeight = $oldHeight*$factor;
        }
        else
        {
            $newWidth = $oldWidth;
            $newHeight = $oldHeight;
        }
        $tmp = imagecreatetruecolor($newWidth,$newHeight);

        imagecopyresized($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);


         imagejpeg($tmp,$filename,80);

        imagedestroy($tmp);
        imagedestroy($src);


        //end

 

it checks upon upload that the image does not exceed size limits and if it does it will resize the image to suit. What i want it to also do is watermark the image with my company watermark for the page. *bottom right corner*. i think the important thing is to keep the image variables the same so the rest of the upload script still executes correctly, names and stuff i mean, Thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.