Jump to content

Resize an image using php


deansaddigh

Recommended Posts

The below code inserts image details to db and uploads pic to folder, can anyone show me how to resize it aswell. please

 

<?php
include("includes/connection.php");

    // Where the file is going to be placed 
    $schoolimage = "SchoolImages/";

//This path will be stored in the database as it does not contain the filename
$currentdir = getcwd();
$path = $currentdir . '/' . $schoolimage;

// Get the schoolid for the image and school linker table
$schoolid = $_POST['schoolid'];

//Get the school name
$query = "SELECT * FROM school WHERE school_id = ".$schoolid;
$result = mysql_query($query) 
	or die("Error getting school details");
$row = mysql_fetch_assoc($result);
$schoolname = $row['name']; 

//Use this path to store the path of the file in the database.
$filepath = $schoolimage . $schoolname;


//Create the folder if it does not already exist
if(!file_exists('SchoolImages'))
    {
        if(mkdir('SchoolImages'))
        {
            echo 'Folder ' . 'SchoolImages' . ' created.';
        }
        else
        {
            echo 'Error creating folder ' . 'SchoolImages';
        }
    }


//Store the folder for the course title.
    if(!file_exists( $filepath ))
    {
        if(mkdir( $filepath ))
        {
            echo 'Folder ' . $schoolname . ' created.';
        }
        else
        {
            echo 'Error creating folder ' . $schoolname;
        }
    }


// Where the file is going to be placed 
    $target_path = $filepath;

    // Add the original filename to our target path. Result is "uploads/filename.extension"
    echo $target_path = $target_path . '/' . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{
	echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
	$filename =  $_FILES['uploadedfile']['name'];

	//Store the filename, path other criteria in the database 
	echo $query = "INSERT INTO image(image_id, name, path)
	VALUES(0, '$filename', '$filepath')";

	//Perform the query
	$add = mysql_query($query, $conn)
		or die("Unable to add the image details to the database");
	$imageid = mysql_insert_id();

	//Store the filename, path other criteria in the database 
	echo $query = "INSERT INTO image_school( image_id, school_id )
	VALUES('$imageid', '$schoolid')";

	//Perform the query
	$add = mysql_query($query, $conn)
		or die("Unable to add the image details to the database");

	$message = 'Upload Successful';
} 
else
{	
	$message = 'There was an error uploading the file, please try again!';
}

//Close the connection to the database	
mysql_close($conn);
header("Location: add_school_photo_form.php? message={$message}&schoolid={$schoolid}");
//header("Location: add_school_photo_form.php? message=$message, schoolid=$schoolid");
exit();

?>

Link to comment
Share on other sites

The best way to do this would be to use somthing like PHPThumb() that uses the GD2 library available on most linux servers.

http://phpthumb.sourceforge.net/

 

or something like this:

 

*//
Note :
- GD must Enabled
- Autodetect file extension (.jpg/jpeg, .png, .gif, .wbmp)
  but some server can't generate .gif / .wbmp file types
- If your GD not support 'ImageCreateTrueColor' function,
  change one line from 'ImageCreateTrueColor' to 'ImageCreate'
  (the position in 'show' and 'save' function)
*/


class thumbnail
{
    var $img;

    function thumbnail($imgfile)
    {
        //detect image format
        $this->img["format"]=ereg_replace(".*\.(.*)$","\\1",$imgfile);
        $this->img["format"]=strtoupper($this->img["format"]);
        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") {
            //JPEG
            $this->img["format"]="JPEG";
            $this->img["src"] = ImageCreateFromJPEG ($imgfile);
        } elseif ($this->img["format"]=="PNG") {
            //PNG
            $this->img["format"]="PNG";
            $this->img["src"] = ImageCreateFromPNG ($imgfile);
        } elseif ($this->img["format"]=="GIF") {
            //GIF
            $this->img["format"]="GIF";
            $this->img["src"] = ImageCreateFromGIF ($imgfile);
        } elseif ($this->img["format"]=="WBMP") {
            //WBMP
            $this->img["format"]="WBMP";
            $this->img["src"] = ImageCreateFromWBMP ($imgfile);
        } else {
            //DEFAULT
            echo "Not Supported File";
            exit();
        }
        @$this->img["lebar"] = imagesx($this->img["src"]);
        @$this->img["tinggi"] = imagesy($this->img["src"]);
        //default quality jpeg
        $this->img["quality"]=75;
    }

    function size_height($size=100)
    {
        //height
        $this->img["tinggi_thumb"]=$size;
        @$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
    }

    function size_width($size=100)
    {
        //width
        $this->img["lebar_thumb"]=$size;
        @$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
    }

    function size_auto($size=100)
    {
        //size
        if ($this->img["lebar"]>=$this->img["tinggi"]) {
            $this->img["lebar_thumb"]=$size;
            @$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
        } else {
            $this->img["tinggi_thumb"]=$size;
            @$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
         }
    }

    function jpeg_quality($quality=75)
    {
        //jpeg quality
        $this->img["quality"]=$quality;
    }

    function show()
    {
        //show thumb
        @Header("Content-Type: image/".$this->img["format"]);

        /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
        $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
            @imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);

        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") {
            //JPEG
            imageJPEG($this->img["des"],"",$this->img["quality"]);
        } elseif ($this->img["format"]=="PNG") {
            //PNG
            imagePNG($this->img["des"]);
        } elseif ($this->img["format"]=="GIF") {
            //GIF
            imageGIF($this->img["des"]);
        } elseif ($this->img["format"]=="WBMP") {
            //WBMP
            imageWBMP($this->img["des"]);
        }
    }

    function save($save="")
    {
        //save thumb
        if (empty($save)) $save=strtolower("./thumb.".$this->img["format"]);
        /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
        $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
            @imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);

        if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") {
            //JPEG
            imageJPEG($this->img["des"],"$save",$this->img["quality"]);
        } elseif ($this->img["format"]=="PNG") {
            //PNG
            imagePNG($this->img["des"],"$save");
        } elseif ($this->img["format"]=="GIF") {
            //GIF
            imageGIF($this->img["des"],"$save");
        } elseif ($this->img["format"]=="WBMP") {
            //WBMP
            imageWBMP($this->img["des"],"$save");
        }
    }
}

Link to comment
Share on other sites

      // This is the temporary file created by PHP

      $uploadedfile = $_FILES['uploadfile']['tmp_name'];

      // Create an Image from it so we can do the resize

      $src = imagecreatefromjpeg($uploadedfile);

      // Capture the original size of the uploaded image

      list($width,$height)=getimagesize($uploadedfile);

      // For our purposes, I have resized the image to be
      // 600 pixels wide, and maintain the original aspect
      // ratio. This prevents the image from being "stretched"
      // or "squashed". If you prefer some max width other than
      // 600, simply change the $newwidth variable

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

      // this line actually does the image resizing, copying from the original
      // image into the $tmp image

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

      // now write the resized image to disk. I have assumed that you want the
      // resized, uploaded image file to reside in the SchoolImages directory.

      $filename = "SchoolImages/". $_FILES['uploadfile']['name'];
      imagejpeg($tmp,$filename,100);
      imagedestroy($src);
      imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request

      // has completed.

 

For more info on how to use the function try here: http://php.net/manual/en/function.imagecreatefromjpeg.php

you can also find out about the getimagesize() function as well, you should be able to intergrate your script into this!

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.