Jump to content

Recommended Posts

hey guys here is my code

<?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> ?>

 

for some reason it doesnt seem to be resizing my images i only want it so its displayed as a profile picture lol and the are turning out huge... any reason why it does not work and guidence or code that will fix it.. ty :)

 

p.s tried google ect and no help me me wat so ever lol

Link to comment
https://forums.phpfreaks.com/topic/86623-image-resizing-not-working/
Share on other sites

what it does is just upload an image to a file and send information to db... does that fine

 

i then call image on a different page

 

this all works fine....

 

the problem i am having is the fact the image does not get resizied by  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 {

 

 

Here i just found this code i tested it and it works with my server

 

function gdresizetofile($source,$dest,$type,$max_width=420,$max_height=500){
// Get sizes
list($width, $height) = getimagesize($source);
//width
if($width>$max_width){
	$divide=$width/$max_width;
	$newwidth=$width/$divide;
	$newheight=$height/$divide;

	// Load
	$image = imagecreatetruecolor($newwidth, $newheight);
	switch(strtolower($type)){
	case 'jpg':
		$old_image = imagecreatefromjpeg($source);
		break;
	case 'gif':
		$old_image = imagecreatefromgif($source);
		break;
	case 'png':
		$old_image = imagecreatefrompng($source);
		break;
	}
	// Resize
	imagecopyresized($image, $old_image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}else{
	switch($type){
	case 'jpg':
		$image = imagecreatefromjpeg($source);
		break;
	case 'gif':
		$image = imagecreatefromgif($source);
		break;
	case 'png':
		$image = imagecreatefrompng($source);
		break;
	}
}
// Output
imagejpeg($image);


}

 

Scott.

function gdresizetofile($source,$dest,$type,$max_width=420,$max_height=500){
// Get sizes
list($width, $height) = getimagesize($source);
//width
if($width>$max_width){
	$divide=$width/$max_width;
	$newwidth=$width/$divide;
	$newheight=$height/$divide;

	// Load
	$image = imagecreatetruecolor($newwidth, $newheight);
	switch(strtolower($type)){
	case 'jpg':
		$old_image = imagecreatefromjpeg($source);
		break;
	case 'gif':
		$old_image = imagecreatefromgif($source);
		break;
	case 'png':
		$old_image = imagecreatefrompng($source);
		break;
	}
	// Resize
	imagecopyresized($image, $old_image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}else{
	switch($type){
	case 'jpg':
		$image = imagecreatefromjpeg($source);
		break;
	case 'gif':
		$image = imagecreatefromgif($source);
		break;
	case 'png':
		$image = imagecreatefrompng($source);
		break;
	}
}
// Output
imagejpeg($image);


}

 

surelly this doesent appear to require a destination but makes no use of it and doesn't return a result?

 

could i some how change the destination paramater to be passed by reference, then use it in the imagecopyresized call and it will alter the original

ok guys still been messin with it  got it a little further but still need help :(

 

ok  this calls my image

<?php $q = mysql_query($sql) or die("Error running query:".mysql_error());

       				 if($q && mysql_num_rows($q) > 0)  {

            		$row = mysql_fetch_array($q);

            		if(!empty($row)) {

                	echo "<img src='http://www.runningprofiles.com/members/images/". $pid . "." . $row['ext']  . "'";

       					 	}

        					else {

            			echo '<img src="images/pic.jpg">';

								}

							}

							?>

and then i have this code that should change the picture to a smaller frame but i dunno how to get it to run with the picture load... any help guys?

 

function imageResize($source, $maxWidth = 420, $maxHeight = 500)
{
    $bNeedsResize = false;
    list ($width, $height, $type) = getimagesize($source);
    $oWidth = $width;
    $oHeight = $height;

    if ($width <= 0 || $height <= 0):
        throw new Exception('Cannot generate image from no height / width!');
    endif;

    // Err, these equations 'look' right, but I can't test them atm to be sure
    if ($width > $maxWidth):
        // Calculate an appropriate width:
        $ratio = $maxWidth / $width;
        $width = ceil($width * $ratio);
        $height = ceil($height * $ratio);
        $bNeedsResize = true;
    endif;
    if ($height > $maxHeight):
        $ratio = $maxHeight / $height;
        $width = ceil($width * $ratio);
        $height = ceil($height * $ratio);
        $bNeedsResize = true;
    endif;
    // Ok, that will resize it to keep it in preportion for both height/width
    $image = imagecreatetruecolor($width, $height);
    $imageFrom = null;
    switch($type):
        case 'jpg':
            $imageFrom = @imagecreatefromjpeg($source);
            break;
        case 'gif':
            $imageFrom = @imagecreatefromgif($source);
            break;
        case 'png':
            $imageFrom = @imagecreatefrompng($source);
            break;
    endswitch;
    
    // Ok, we got ourself an new image.  Looks like it will require a JPG output,
    // but lets see if we need to resize it first:
    if ($bNeedsResize):
        if (!imagecopyresized($image, $imageFrom, 0, 0, 0, 0, $width, $height, $oWidth, $oHeight)):
            throw new Exception('Could not resize image!');
        endif;
    else:
        // Ok, we don't need to resize it:
        $image = $imageFrom;
    endif;
    
    header('Content-type: image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
}  

ok lets start again seems no 1 knows :P

 

<?php
  session_start();
  require_once '../settings.php';
  
  if(!$_POST['uploaded']){
    /**
     * 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>

<?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');
          }          }
        }
      }
    /* 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>';
  }


?> [code]

how can i make an image loaded like that be resizied

[/code]

ok i got image resize working ...

<?php


//load the config file
include("config.php");
require_once '../settings.php';


//if the for has submittedd
if (isset($_POST['upForm'])){

       $file_type = $_FILES['imgfile']['type'];
       $file_name = $_FILES['imgfile']['name'];
       $file_size = $_FILES['imgfile']['size'];
       $file_tmp = $_FILES['imgfile']['tmp_name'];

       //check if you have selected a file.
       if(!is_uploaded_file($file_tmp)){
          echo "Error: Please select a file to upload!. <br>--<a href=\"$_SERVER[php_SELF]\">back</a>";
          exit(); //exit the script and don't do anything else.
       }
       //check file extension
       $ext = strrchr($file_name,'.');
       $ext = strtolower($ext);
       if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
          echo "Wrong file extension.  <br>--<a href=\"$_SERVER[php_SELF]\">back</a>";
          exit();
       }
       //get the file extension.
       $getExt = explode ('.', $file_name);
       $file_ext = $getExt[count($getExt)-1];

//get users ID
    $id = $_SESSION['user_id'];
    
      
      //get the new width variable.
       $ThumbWidth = $img_thumb_width;

       //keep image type
       if($file_size){
          if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
               $new_img = imagecreatefromjpeg($file_tmp);
           }elseif($file_type == "image/x-png" || $file_type == "image/png"){
               $new_img = imagecreatefrompng($file_tmp);
           }elseif($file_type == "image/gif"){
               $new_img = imagecreatefromgif($file_tmp);
           }
           //list width and height and keep height ratio.
           list($width, $height) = getimagesize($file_tmp);
           $imgratio=$width/$height;
           if ($imgratio>1){
              $newwidth = $ThumbWidth;
              $newheight = $ThumbWidth/$imgratio;
           }else{
                 $newheight = $ThumbWidth;
                 $newwidth = $ThumbWidth*$imgratio;
           }
           //function for resize image.
           if (function_exists(imagecreatetruecolor)){
           $resized_img = imagecreatetruecolor($newwidth,$newheight);
           }else{
                 die("Error: Please make sure you have GD library ver 2+");
           }
           imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
           //save image
           ImageJpeg ($resized_img,"$path_thumbs/$id.$file_ext");
           ImageDestroy ($resized_img);
           ImageDestroy ($new_img);
           //print message
           echo "<br>Image Thumb: <a href=\"$path_thumbs/$id.$file_ext\">$path_thumbs/$id.$file_ext</a>";
        }

        //upload the big image
        move_uploaded_file ($file_tmp, "$path_big/$id.$file_ext");

        echo "<br>Image Big: <a href=\"$path_big/$id.$file_ext\">$path_big/$id.$file_ext</a>";

        echo "<br><br>--<a href=\"$_SERVER[php_SELF]\">back</a>";

}else{ //if the form hasn't been submitted.

      //print the form
      echo "<script>
      function view_img(img_name){
         document[img_name].src = upForm.imgfile.value;
            document[img_name].width = 150;
      }
      </script>\n\n
      <br><h3>:: Browse an Image to Upload:</h3>\n
      <form method=\"post\" name=\"upForm\" enctype=\"multipart/form-data\" action=\"$_SERVER[php_SELF]\">\n
      <input type=\"file\" name=\"imgfile\" onchange=\"javascript:view_img('img_vv');\"> <img src='' name='img_vv' width='0'><br>\n
      Image width will resize to <b>$img_thumb_width</b> with height ratio.
      <br><input type=\"Submit\" name=\"upForm\" value=\"Upload & Resize\">\n
      </form>
      <a href=\"view_gallery.php\">View Images</a>";

}


?> 

 

but it wont rename the image to user id ???  $id = $_SESSION['user_id'];

 

that got through going to require_once '../settings.php'; which then directs you to require ( 'functions.php' ); then in that it has

 

 

 function checkLogin ( $levels )
{
	session_start ();
	global $db;
	$kt = split ( ' ', $levels );

	if ( ! $_SESSION['logged_in'] ) {

		$access = FALSE;

		if ( isset ( $_COOKIE['cookie_id'] ) ) {//if we have a cookie

			$query =  'SELECT * FROM ' . DBPREFIX . 'users WHERE ID = ' . $db->qstr ( $_COOKIE['cookie_id'] );

			if ( $db->RecordCount ( $query ) == 1 ) {//only one user can match that query
				$row = $db->getRow ( $query );

				//let's see if we pass the validation, no monkey business
				if ( $_COOKIE['authenticate'] == md5 ( getIP () . $row->Password . $_SERVER['USER_AGENT'] ) ) {
					//we set the sessions so we don't repeat this step over and over again
					$_SESSION['user_id'] = $row->ID;				
					$_SESSION['logged_in'] = TRUE;

					//now we check the level access, we might not have the permission
					if ( in_array ( get_level_access ( $_SESSION['user_id'] ), $kt ) ) {
						//we do?! horray!
						$access = TRUE;
					}
				}
			}
		}
	}
	else {			
		$access = FALSE;

		if ( in_array ( get_level_access ( $_SESSION['user_id'] ), $kt ) ) {
			$access = TRUE;
		}
	}

	if ( $access == FALSE ) {
		header('Location: http://runningprofiles.com/members/index.php');
	}		
}

 

 

but all i get is  Image Thumb: images/thumbs/.jpg    were is users id?

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.