Jump to content

Recommended Posts

Resizing & Uploading an image

 

I've been playing around with this for a while now. Basically what I want to do is a user uploads a picture to the server via a form. During the upload I would like the picture to be resized and saved (overwriting itself and saving the resized image).

 

I've got some code; I can upload images to the server via a form, I can also resize images and save/overwrite the images. What I can't quite do is both at the same time!

 

I have 3 pages, one is a basic html upload form.

 

 

Another is this file which is called when image is uploaded (this also shows the resulting uploaded fields/image):

 

//This is the directory where images will be saved 
$target = "pictures/"; 
$target = $target . basename( $_FILES['photo']['name']); 

//This gets all the other information from the form 
$name=$_POST['name']; 
$Title=$_POST['Title']; 
$Item=$_POST['Item']; 
$pic=($_FILES['photo']['name']); 

// Connects to your Database 
mysql_connect("localhost", "username", "password") or die(mysql_error()) ; 
mysql_select_db("database") or die(mysql_error()) ; 

//Writes the information to the database 
mysql_query("INSERT INTO table VALUES ('$id' , '$Title', '$Item', '$pic', '$name')") ; 

//Writes the photo to the server 
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 

//Tells you if its all ok 
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information 

has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
}

  $query="SELECT * FROM table ORDER BY id DESC LIMIT 1";

  $result=mysql_query($query);

  while($row=mysql_fetch_array($result, MYSQL_ASSOC)){

include('SimpleImage.php');
$image = new SimpleImage();
   $image->load(pictures/$row['photo']);
   $image->resizeToWidth(350);
   $image->save(pictures/$row['photo']);

  ?>

<table width="800" border="1" bordercolor="#0a50a1" bgcolor="#ffffff" align="center" cellpadding="0" 

cellspacing="0"><tr><td><table width="100%" border="0" bgcolor="#ffffff" align="center" cellpadding="8" 

cellspacing="0">
<tr>
<td align="left"><? echo "<img src=http://www.domain/pictures/".$row['photo'].">"; 

?></td></tr>
<tr><td align="left" style="font-family: verdana; font-size: .8em; color: #0a50a1"><b><? echo $row

['Title'];?></b><br><br>
<? echo $row['Item'];?></td></tr></table></td></tr></table>
<br>

<?

  }

  ?>



 

And the last file is obviously the 'SimpleImage.php' page. I'm just really struggling getting the above code right. In it's present state it uploads the image and displays the fields and image, but does not resize it and throws up a lot of errors. I THINK(!) it's just how I've written the above file, I can't quite grasp what is wrong.

 

Hope someone can give me a couple of pointers! Thanks! ;-)

 

 

Link to comment
https://forums.phpfreaks.com/topic/190946-resizing-uploading-an-image/
Share on other sites

Have been looking at this again....perhaps I need to call the 'SimpleImage.php' file from my page with the form on it? Something like:

 

<?php
   if( isset($_POST['submit']) ) {
      include('SimpleImage.php');
      $image = new SimpleImage();
      $image->load($_FILES['photo']['tmp_name']);
      $image->resizeToWidth(150);
      $image->output();
   } else {
?>


<form enctype="multipart/form-data" action="add-resize.php" method="POST">  
Title: <input type="text" name = "Title"><br> 
Article: <input type="text" name = "Item"><br> 
Photo: <input type="file" name="photo"><br>
Name: <input type="text" name="name"><br> 
<input type="submit" name="submit" value="Add"> 
</form>

<?php

}

?>

 

But I still haven't got it right! What am I missing?  :confused:

here is code that will do just that, post to this file and you can resize image before saving,

 

you will have to make it work for you, and it will handle one upload at a time....

 

hope it helps...

 

the function createthumbnail() is the resizer

 

play with it

 

<?php
session_start();
if(!session_is_registered(username)){
header("location: ../../login2/app_login.php");
}
$result = null;
//includes. 
include '../../login/dirconf.php';

// create the users folder in not yet created.
if (!is_dir("../users/$username"))
{
mkdir("../users/$username", 0751);
}

Function createthumbnail($src=null) {
$srcimg = imagecreatefromjpeg($src);
 $srcsize = getimagesize($src);
 $dest_y = 900;
 $dest_x = (900 / $srcsize[1]) * $srcsize[0];
$thumbimg = imagecreatetruecolor($dest_x, $dest_y);
imagecopyresampled($thumbimg,$srcimg,0,0,0,0,$dest_x,$dest_y, $srcsize[0], $srcsize[1]);
imagejpeg($thumbimg,$src);
}

//form data.
$pinf = $_POST['pinf']; 
$tag = $_POST['tag'];
$disp = $_POST['disp'];

//test remove whitespace and replace with _

$rawname = ($_FILES['imagefile']['name']);
$newname = str_replace(" ", "_", $rawname);


$location = "../users/$username/";
$location = $location . basename($newname);
$target = "users/$username/";
$target = $target . basename($newname);
$img = $target;
$filesize = ($_FILES['imagefile']['size']);
$filename = $newname;
$filetype = ($_FILES['imagefile']['type']);

//open connection to database server.
$connection = mysql_connect($host, $user, $pass) or die ('unable to connect!');
//select  database to use.
mysql_select_db($db) or die ('unable to select database!');

//test filename exist
$query = "select phname from uphotos where fk_uid = '" . $userid . "' and phname = '" . $filename . "'";
$result = mysql_query($query);

//test if file exist.
if(mysql_num_rows($result) > 0)
{
//close database
mysql_close($connection);
$_SESSION['error'] = "file name exist already!";
header("location: get_manager_images.php?up=true");
exit();
}
//requery to get all rows for a user.
$query = "select phname from uphotos where fk_uid = '" .$userid. "'";
$result = mysql_query($query);	
//should allow 8 files.
if(mysql_num_rows($result) > 7)
{ 
//close database
mysql_close($connection);
$_SESSION['error'] = "you have reached your upload limit!";
header("location: get_manager_images.php?up=true");
exit();
}
//test file. 
elseif ($filetype = 'image/jpeg')
{
if($filesize > 0) {
	if($filesize > 600000)
	{
		createthumbnail($_FILES['imagefile']['tmp_name']);
	}
	if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $location))
	{
		if(!get_magic_quotes_gpc())
   	{
      	$fileName = addslashes($fileName);
   	}
		$query = "INSERT INTO uphotos (fk_uid, phtag, phname, size, content, inf, disp)
	             VALUES ('".$userid."', '".$tag ."', '".$filename."', '".$filesize."', '".$img."', '".$pinf."', '".$disp."')";
	   $result = mysql_query($query) or die ('error3 in query: $query. ' . mysql_error()); 


		$updatetime = time();
		$update = "added photo";
		//$query = "update friendupdates set friendupdate = 'added a new photo', time = '".$updatetime."' where userid = '".$userid."'";
		$query = "insert into updates (uid,value,time) values ('".$userid."','".$update."','".$updatetime."')";
		$result = mysql_query($query);			

		//close database
		mysql_close($connection);

		//redirect
		header("location: get_manager_images.php");//?up=true");
		exit();
	}
}
else
{
	$_SESSION['error'] = "there was an error with your upload, please check file size 3mb max size.";
	header("location: get_manager_images.php?up=true");
	exit(); 
}
}
else
{
$_SESSION['error'] = "there was an error with your upload, please check file type, only jpeg images.";
header("location: get_manager_images.php?up=true");
exit(); 
}		
?> 

Hi guys - thanks for the replies! Ah...I see that would make more sense. Thanks for the code - I will have a play with that tonight once my toddler is in bed (looking after a mad two year old and concentrating on PHP code do not mix!!!)  :P

Hi guys - thanks for the replies! Ah...I see that would make more sense. Thanks for the code - I will have a play with that tonight once my toddler is in bed (looking after a mad two year old and concentrating on PHP code do not mix!!!)  :P

 

yes they can if you give him/her a lil bit of what my avatar is havin' :D

I much prefer using imagemagick to resample images as opposed to php's native GD library functions. It works much better. You can execute its commands via php's exec() function. For more info on installing imagemagick and it's usage go to the website and take a look at the command line tools: http://www.imagemagick.org/script/index.php

 

I've noticed that most hosting companies have this pre-installed on their servers.

Oh no, more options - thank you! LOL! Well I decided to start a poll here:

http://www.phpfreaks.com/forums/index.php/topic,286915.msg1360370.html#msg1360370

 

To see what the general opinion is on image manipulation..... yes, I genuinely want to know ;)  :P!

Well, to cut a long story short, I am not currently able to use imagemagick to resize my images, so have managed to get my code working thus (with thanks to meomike2000!!):

 

<?php 

Function createthumbnail($src=null) {
$srcimg = imagecreatefromjpeg($src);
$srcsize = getimagesize($src);
$dest_x = 350;
$dest_y = (350 / $srcsize[0]) * $srcsize[1];
$thumbimg = imagecreatetruecolor($dest_x, $dest_y);
imagecopyresampled($thumbimg,$srcimg,0,0,0,0,$dest_x,$dest_y, $srcsize[0], $srcsize[1]);
imagejpeg($thumbimg,$src);
}

//This is the directory where images will be saved 
$target = "pictures/"; 
$target = $target . basename( $_FILES['photo']['name']); 

//This gets all the other information from the form 
$name=$_POST['name']; 
$Title=$_POST['Title']; 
$Item=$_POST['Item']; 
$pic=($_FILES['photo']['name']); 

// Connects to your Database 
mysql_connect("host", "username", "password") or die(mysql_error()) ; 
mysql_select_db("database") or die(mysql_error()) ; 

//Writes the information to the database 
mysql_query("INSERT INTO table VALUES ('$id' , '$Title', '$Item', '$pic', '$name')") ; 

//Writes the photo to the server

createthumbnail($_FILES['photo']['tmp_name']);

if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 

{ 

//Tells you if its all ok 
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to 

the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
}

  $query="SELECT * FROM newsarticles ORDER BY id DESC LIMIT 1";

  $result=mysql_query($query);

  while($row=mysql_fetch_array($result, MYSQL_ASSOC)){

  ?>

<table width="800" border="1" bordercolor="#0a50a1" bgcolor="#ffffff" align="center" cellpadding="0" 

cellspacing="0"><tr><td><table width="100%" border="0" bgcolor="#ffffff" align="center" cellpadding="8" cellspacing="0">
<tr>
<td align="left"><? echo "<img src=http://www.website.com/pictures/".$row['photo'].">"; ?></td></tr>
<tr><td align="left" style="font-family: verdana; font-size: .8em; color: #0a50a1"><b><? echo $row['Title'];?></b><br><br>
<? echo $row['Item'];?></td></tr></table></td></tr></table>

<?
  }
  ?>

 

There is just one thing I still want to try and do; if the image to be uploaded is smaller than the required size (ie 350px) then I don't want it to be resized.

 

I have been trying with something like or some combination of:

if ($srcsize > 350){
createthumbnail($_FILES['photo']['tmp_name']);
}
else
{
just upload image!!

 

But obviously I'm writing it wrong and also putting it in the wrong place!! Could someone point me in the right direction please before I tear my last hair out (lol!)  :P

You are using the getimagesize() function within the scope of the function, so you have 2 options.

1. Get the image size outside of the function and pass the height & width in as parameters

2. Pass the minimum height and width into the function as parameters and ony get the function to perform a resize if the values are above the passed in values after using getimagesize(). If they arent just return false from the function.

Thanks for the advice guys! Managed to get it to work ** :o amaze!** Thought I would post my code incase it might help someone else:

 

// Resize image during upload if larger than maximum allowed size.
Function createthumbnail($src=null) {
$srcimg = imagecreatefromjpeg($src);

// Get size of original image:
$srcsize = getimagesize($src);

// Specify maximum image width / height allowed:
$my_size = 350;

// If the original image width and height are greater than $my_size, resize to the maximum image width / height allowed:
if($srcsize[0] > $my_size && $srcsize[1] > $my_size) {
$dest_x = 350;
$dest_y = (350 / $srcsize[0]) * $srcsize[1];
$thumbimg = imagecreatetruecolor($dest_x, $dest_y);
imagecopyresampled($thumbimg,$srcimg,0,0,0,0,$dest_x,$dest_y, $srcsize[0], $srcsize[1]);
imagejpeg($thumbimg,$src);
}
}

 

Thanks for your help!  ;)

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.