Jump to content

image resize help


KDM

Recommended Posts

I did a tutorial on uploading a profile pic and also did a tutorial on an image re-size class. The only thing is the tutorial on the re-size class is done without using a form which is pointless. Can someone help me integrate this into the profile pic tutorial? Here's a link to the re-size tutorial.

 

http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/comment-page-3/#comment-401884

 

index.php

<?php
session_start();

//include the class
include("resize-class.php");

//1 initialize / load image
$resizeObj = new resize('sample.jpg');

//2 Resize image (options: exact, potrait, landscape, auto, crop)
$resizeObj -> reseizeImage(150,100, 'crop');

//3 Save image
$resizeObj -> saveImage('sample-resized.gif', 100);




include "connect.php";

$_SESSION['username']='Anomalous';
$username = $_SESSION['username'];

if ($_POST['submit'])
{
    //get file attributes
    $name = $_FILES['myfile']['name'];
    $tmp_name = $_FILES['myfile']['tmp_name'];

    if ($name)
    {
        //start upload process
        $location = "avatars/$name";
        move_uploaded_file($tmp_name,$location);

        $query = mysql_query("UPDATE users SET image='$location' WHERE username='$username'");

        die("Your profile pic has been uploaded! <a href='view.php'>My Profile</a>");


    }
    else
die("Please select a file!");

}

echo "Welcome, ".$username."!<p>";

echo "Upload your image:
<form action='index.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='myfile'> <input type='submit' name='submit' value='Upload!'>
</form>";

?>

 

resize-class.php

<?php

   # ========================================================================#
   #
   #  Author:    Jarrod Oberto
   #  Version:	 1.0
   #  Date:      17-Jan-10
   #  Purpose:   Resizes and saves image
   #  Requires : Requires PHP5, GD library.
   #  Usage Example:
   #                     include("classes/resize_class.php");
   #                     $resizeObj = new resize('images/cars/large/input.jpg');
   #                     $resizeObj -> resizeImage(150, 100, 0);
   #                     $resizeObj -> saveImage('images/cars/large/output.jpg', 100);
   #
   #
   # ========================================================================#


	Class resize
	{
		// *** Class variables
		private $image;
	    private $width;
	    private $height;
		private $imageResized;

		function __construct($fileName)
		{
			// *** Open up the file
			$this->image = $this->openImage($fileName);

		    // *** Get width and height
		    $this->width  = imagesx($this->image);
		    $this->height = imagesy($this->image);
		}

		## --------------------------------------------------------

		private function openImage($file)
		{
			// *** Get extension
			$extension = strtolower(strrchr($file, '.'));

			switch($extension)
			{
				case '.jpg':
				case '.jpeg':
					$img = @imagecreatefromjpeg($file);
					break;
				case '.gif':
					$img = @imagecreatefromgif($file);
					break;
				case '.png':
					$img = @imagecreatefrompng($file);
					break;
				default:
					$img = false;
					break;
			}
			return $img;
		}

		## --------------------------------------------------------

		public function resizeImage($newWidth, $newHeight, $option="auto")
		{
			// *** Get optimal width and height - based on $option
			$optionArray = $this->getDimensions($newWidth, $newHeight, $option);

			$optimalWidth  = $optionArray['optimalWidth'];
			$optimalHeight = $optionArray['optimalHeight'];


			// *** Resample - create image canvas of x, y size
			$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
			imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);


			// *** if option is 'crop', then crop too
			if ($option == 'crop') {
				$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
			}
		}

		## --------------------------------------------------------

		private function getDimensions($newWidth, $newHeight, $option)
		{

		   switch ($option)
			{
				case 'exact':
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
					break;
				case 'portrait':
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					$optimalHeight= $newHeight;
					break;
				case 'landscape':
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
					break;
				case 'auto':
					$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
					break;
				case 'crop':
					$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
					break;
			}
			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

		## --------------------------------------------------------

		private function getSizeByFixedHeight($newHeight)
		{
			$ratio = $this->width / $this->height;
			$newWidth = $newHeight * $ratio;
			return $newWidth;
		}

		private function getSizeByFixedWidth($newWidth)
		{
			$ratio = $this->height / $this->width;
			$newHeight = $newWidth * $ratio;
			return $newHeight;
		}

		private function getSizeByAuto($newWidth, $newHeight)
		{
			if ($this->height < $this->width)
			// *** Image to be resized is wider (landscape)
			{
				$optimalWidth = $newWidth;
				$optimalHeight= $this->getSizeByFixedWidth($newWidth);
			}
			elseif ($this->height > $this->width)
			// *** Image to be resized is taller (portrait)
			{
				$optimalWidth = $this->getSizeByFixedHeight($newHeight);
				$optimalHeight= $newHeight;
			}
			else
			// *** Image to be resizerd is a square
			{
				if ($newHeight < $newWidth) {
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
				} else if ($newHeight > $newWidth) {
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					$optimalHeight= $newHeight;
				} else {
					// *** Sqaure being resized to a square
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
				}
			}

			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

		## --------------------------------------------------------

		private function getOptimalCrop($newWidth, $newHeight)
		{

			$heightRatio = $this->height / $newHeight;
			$widthRatio  = $this->width /  $newWidth;

			if ($heightRatio < $widthRatio) {
				$optimalRatio = $heightRatio;
			} else {
				$optimalRatio = $widthRatio;
			}

			$optimalHeight = $this->height / $optimalRatio;
			$optimalWidth  = $this->width  / $optimalRatio;

			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

		## --------------------------------------------------------

		private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
		{
			// *** Find center - this will be used for the crop
			$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
			$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

			$crop = $this->imageResized;
			//imagedestroy($this->imageResized);

			// *** Now crop from center to exact requested size
			$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
			imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
		}

		## --------------------------------------------------------

		public function saveImage($savePath, $imageQuality="100")
		{
			// *** Get extension
        		$extension = strrchr($savePath, '.');
       			$extension = strtolower($extension);

			switch($extension)
			{
				case '.jpg':
				case '.jpeg':
					if (imagetypes() & IMG_JPG) {
						imagejpeg($this->imageResized, $savePath, $imageQuality);
					}
					break;

				case '.gif':
					if (imagetypes() & IMG_GIF) {
						imagegif($this->imageResized, $savePath);
					}
					break;

				case '.png':
					// *** Scale quality from 0-100 to 0-9
					$scaleQuality = round(($imageQuality/100) * 9);

					// *** Invert quality setting as 0 is best, not 9
					$invertScaleQuality = 9 - $scaleQuality;

					if (imagetypes() & IMG_PNG) {
						 imagepng($this->imageResized, $savePath, $invertScaleQuality);
					}
					break;

				// ... etc

				default:
					// *** No extension - No save.
					break;
			}

			imagedestroy($this->imageResized);
		}


		## --------------------------------------------------------

	}
?>

 

view.php

<?php

include ("connect.php");

$username = $_SESSION['username'];

echo $username;


$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($query)==0)
    die("user not found");
else
{
    $row = mysql_fetch_assoc($query);
    $location = $row['image'];

    echo "<img src='$location'>";
}

?>

 

 

connect.php

<?php
session_start();

mysql_connect('localhost', 'root', 'root');
mysql_select_db('DB');

?>

Link to comment
Share on other sites

So you need help implementing and integrating a bunch of code you don't understand?

 

I suggest the freelance forum.

 

If you're trying to learn PHP, this is a bad way to do it. You're diving in head first using code you've copied and pasted and don't understand. What happens when an error pops up? How will you be able to check for errors if you don't understand how the class works? Is there even any error reporting within the class?

 

If your goal is to simply get this working, and maybe get a little insight as to how it's done, you should hire a developer. Ask them to comment the code, or see if they'll allow you to 'watch in' on the work, and provide commentary.

Link to comment
Share on other sites

The only thing is the tutorial on the re-size class is done without using a form which is pointless.

How is that pointless.

 

1) I can think of several scenarios where resizing an existing image (i.e. not submitted via a for) would be valid

2) When a user uploads a pic it has to go "somewhere". If the resizing script works on existing images you should know "where' the image is after you upload it.

Link to comment
Share on other sites

So you need help implementing and integrating a bunch of code you don't understand?

 

I suggest the freelance forum.

 

If you're trying to learn PHP, this is a bad way to do it. You're diving in head first using code you've copied and pasted and don't understand. What happens when an error pops up? How will you be able to check for errors if you don't understand how the class works? Is there even any error reporting within the class?

 

If your goal is to simply get this working, and maybe get a little insight as to how it's done, you should hire a developer. Ask them to comment the code, or see if they'll allow you to 'watch in' on the work, and provide commentary.

 

I didn't copy / paste anything. I did both tutorials, I don't know how to combine the two. It seems that's the best way to learn, by hiring developers and having them comment the code.  I've wasted so much time on forums and tutorials that aren't practical.

Link to comment
Share on other sites

So you need help implementing and integrating a bunch of code you don't understand?

 

I suggest the freelance forum.

 

If you're trying to learn PHP, this is a bad way to do it. You're diving in head first using code you've copied and pasted and don't understand. What happens when an error pops up? How will you be able to check for errors if you don't understand how the class works? Is there even any error reporting within the class?

 

If your goal is to simply get this working, and maybe get a little insight as to how it's done, you should hire a developer. Ask them to comment the code, or see if they'll allow you to 'watch in' on the work, and provide commentary.

 

I didn't copy / paste anything. I did both tutorials, I don't know how to combine the two. It seems that's the best way to learn, by hiring developers and having them comment the code.  I've wasted so much time on forums and tutorials that aren't practical.

 

A tutorial is not meant to be an exact fit for any one implementation. It is meant to instruct the user on the basic processes to complete a task. It is up to the developer to determine how to modify the code to his/her specific needs and implementation.

Link to comment
Share on other sites

So you need help implementing and integrating a bunch of code you don't understand?

 

I suggest the freelance forum.

 

If you're trying to learn PHP, this is a bad way to do it. You're diving in head first using code you've copied and pasted and don't understand. What happens when an error pops up? How will you be able to check for errors if you don't understand how the class works? Is there even any error reporting within the class?

 

If your goal is to simply get this working, and maybe get a little insight as to how it's done, you should hire a developer. Ask them to comment the code, or see if they'll allow you to 'watch in' on the work, and provide commentary.

 

I didn't copy / paste anything. I did both tutorials, I don't know how to combine the two. It seems that's the best way to learn, by hiring developers and having them comment the code.  I've wasted so much time on forums and tutorials that aren't practical.

 

A tutorial is not meant to be an exact fit for any one implementation. It is meant to instruct the user on the basic processes to complete a task. It is up to the developer to determine how to modify the code to his/her specific needs and implementation.

 

Yea but I learn by code. I can not write code out of thin air yet. I can manipulate some code to do what I want but not everything. Lol @ people who expect someone learning php to be an expert after a couple of tutorials.  I often get discouraged, but I know a lot more about php then I did a year ago and that's enough to make me keep going.

Link to comment
Share on other sites

You've shown absolutely no understanding of the code you presented, whether you've typed it by hand, or copied and pasted it.

 

We don't expect you to be an expert after reading a few tutorials. We do expect you to understand code you've posted, and to ask a question directly related to code you've posted.

 

You have posted code you do not understand. You make a comment proving you don't understand how to implement the code you don't understand (even though examples are given). How can we help without simply providing the solution for you?

 

You've managed to create a file, and store it's relative location in a variable. You've even inserted that value into the database. It doesn't take an expert to take that variable and plug it into the resize class.

 

If you continue 'learning' the way you have for the last year, you'll be forever asking others to code and fix errors for you.

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.