Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

uploading and editing images

Status
Not open for further replies.

BPMan

Programmer
Jun 25, 2002
163
0
0
US
i have used php image functions or worked with images, but here is what i want to do, is it possible and if so how do i do it:

i am being passed the path where the file is located

so i want to upload the file to my server
change the name
and esize the image

are there functions for this??
 
yes...

see Handling file uploads

also covers filename changes...

here is some code I found on hotscripts.com

Code:
<html>
<head>
<title>Image resizer 4.1, by Yuriy Horobey</title>
<meta name="description" content="PHP script demonstrating how to resize image to fit given dimensions.">
<meta name="Author" content="Yuriy Horobey, yg108@softhome.net">
</head>
<body>
This script was developed by <a href="mailto:yg108@softhome.net, yg108@rambler.ru?subject=Image Resizer Question">Yuriy 
Horobey.</a><br>
It is freeware, demonstrating my skills working with PHP, you may use it as you want.<br>
If you have some PHP/MySQL job let me know.<br>
<h1>Image resizer 4.1</h1>
<FORM action="imgresizer41.php" encType="multipart/form-data" method="post" name="sendform">
	<INPUT name=MAX_FILE_SIZE type=hidden value=10000000> 
	<INPUT maxLength=128 name=image type=file   ACCEPT="image/gif, image/jpeg, image/jpg">
	<br>
	Name:<INPUT maxLength=128 name="img_name" type="text">
   <br>
	<INPUT name=Submit type=submit value=Submit> 
	<INPUT name=Reset  type=reset value=Reset> 
</FORM>
<p>
<b>If you need some custom programming you can order it online <a href="[URL unfurl="true"]http://expert.phptalk.com">http://expert.phptalk.com</a></b>[/URL]
</p>
<?PHP
#############################################################################################
$IMG_ORG_HEIGHT	= "250";	#Width of original image stored on server
$IMG_ORG_WIDTH  = "250";	#Height of original image stored on server
						#set to "*" to prevent resizing on the dimension
						#you will not lost X to Y ratio 
						
$IMG_HEIGHT = 108;   	# Accepted height of resized image
$IMG_WIDTH  = 108;   	# Accepted width of resized image
						# read about "*" above

$IMG_ROOT = "./img4";		# Relative path to folder where uploaded images will be stored; no ending slash! 
			# Like this: $IMG_ROOT = "./img";	
			# Remeber to set proper attributes to that folder. 777 will work :)
$use_imagecreatetruecolor = false; // these flags enble ImageCreateTrueColor(); ImageCopyResampled();
$use_imagecopyresampled	  = false;// I cant test them coz my host doesn't allow these...
$JPG_QUALITY	=	90; // output jpeg quality

#############################################################################################
//error_reporting(53); // dont need ur warnings!
if(!$HTTP_POST_FILES ["image"]["tmp_name"] || $HTTP_POST_FILES ["image"]["tmp_name"] =="none") die("<br>");

if( ! $f_org = resizer_main("image","",$IMG_ORG_WIDTH,$IMG_ORG_HEIGHT))die("<br><font color=\"red\"><b>No Image received...</b></font><br>");
if( ! $f_res = resizer_main("image","res_",$IMG_WIDTH,$IMG_HEIGHT))die("<br><font color=\"red\"><b>Not resized :( </b></font><br>");


$sz_org =getimagesize( "$IMG_ROOT/$f_org" );
$sz_res =getimagesize( "$IMG_ROOT/$f_res" );
$fs_org= filesize("$IMG_ROOT/$f_org" );
$fs_res= filesize("$IMG_ROOT/$f_res" );

$html =<<< EHTML
<table width="80%" border="1" align="center">
  <tr> 
    <td colspan="2"><b>Original image:</b></td>
  </tr>
  <tr> 
    <td colspan="2">
      <div align="center"><img src="$IMG_ROOT/$f_org" $sz_org[3]></div>
    </td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">Size allowed: </div>
    </td>
    <td width="53%">$IMG_ORG_WIDTH x $IMG_ORG_HEIGHT</td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">Size saved: </div>
    </td>
    <td width="53%">$sz_org[0] x $sz_org[1]</td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">File size: </div>
    </td>
    <td width="53%">$fs_org</td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">JPG Quality: </div>
    </td>
    <td width="53%">$JPG_QUALITY</td>
  </tr>

  <tr> 
    <td colspan="2"><b>Resized image:</b></td>
  </tr>
  <tr> 
    <td colspan="2">
      <div align="center"><img src="$IMG_ROOT/$f_res" $sz_res[3]></div>
    </td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">Size allowed: </div>
    </td>
    <td width="53%">$IMG_WIDTH x $IMG_HEIGHT</td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">Size saved: </div>
    </td>
    <td width="53%">$sz_res[0] x $sz_res[1]</td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">File size: </div>
    </td>
    <td width="53%">$fs_res</td>
  </tr>
  <tr> 
    <td width="47%"> 
      <div align="right">JPG Quality: </div>
    </td>
    <td width="53%">$JPG_QUALITY</td>
  </tr>
</table>
EHTML;

echo $html;




#############################################################################################

function resizer_main($image, $dest_file_prefix,$w, $h){
//image_name = uploaded image. Name or your file field in your form.
//w,h - width and height to fit image in
global $use_imagecreatetruecolor, $use_imagecopyresampled, $IMG_ROOT, $JPG_QUALITY, $HTTP_POST_FILES;
$image_name = $HTTP_POST_FILES [$image]["name"];
$image = $HTTP_POST_FILES [$image]["tmp_name"];

if(trim($image) == "" || trim($image) =="none") return false;

	$arr_img = image_from_upload($image);
	if( $arr_img["w"] != $w && $arr_img["h"] != $h){
		$wh	= get_sizes($arr_img["w"], $arr_img["h"], $w, $h);
		$img_res = img_get_resized(
			$arr_img["img"], 
			$arr_img["w"],	$arr_img["h"], 
			$wh["w"],		$wh["h"], 
			$use_imagecreatetruecolor, 
			$use_imagecopyresampled);
	} else {
			//wow it is exactly like needed!!!
			$img_res = $arr_img["img"];
	}
	$file_name = make_filename($image_name);

	ImageJPEG($img_res,"$IMG_ROOT/$dest_file_prefix$file_name", $JPG_QUALITY);

	return "$dest_file_prefix$file_name";
}

function image_from_upload($uploaded_file){

	$img_sz =  getimagesize( $uploaded_file ); 	## returns array with some properties like dimensions and type;
	####### Now create original image from uploaded file. Be carefull! GIF is often not supported, as far as I remember from GD 1.6
	switch( $img_sz[2] ){
		case 1: 
			$img_type = "GIF";
			$img = ImageCreateFromGif($uploaded_file); 
		break;
		case 2: 
			$img = ImageCreateFromJpeg($uploaded_file); 
			$img_type = "JPG";
		break;
		case 3: 
			$img = ImageCreateFromPng($uploaded_file); 
			$img_type = "PNG";
		break;
		case 4: 
			$img = ImageCreateFromSwf($uploaded_file); 
			$img_type = "SWF";
		break;
		default: die("<br><font color=\"red\"><b>Sorry, this image type is not supported yet.</b></font><br>");
	}//case
	return array("img"=>$img, "w"=>$img_sz[0], "h"=>$img_sz[1], "type"=>$img_sz[2], "html"=>$img_sz[3]);

}


function get_sizes($src_w, $src_h, $dst_w,$dst_h ){
	//src_w ,src_h-- start width and height
	//dst_w ,dst_h-- end width and height
	//return array  w=>new width h=>new height mlt => multiplier
	//the function tries to shrink or enalrge src_w,h in such a way to best fit them into dst_w,h
	//keeping x to y ratio unchanged
	//dst_w or/and dst_h can be "*" in this means that we dont care about that dimension
	//for example if dst_w="*" then we will try to resize by height not caring about width 
	//(but resizing width in such a way to keep the xy ratio)
	//if both = "*" we dont resize at all.
	#### Calculate multipliers
	$mlt_w = $dst_w / $src_w;
	$mlt_h = $dst_h / $src_h;

	$mlt = $mlt_w < $mlt_h ? $mlt_w:$mlt_h;
	if($dst_w == "*") $mlt = $mlt_h;
	if($dst_h == "*") $mlt = $mlt_w;
	if($dst_w == "*" && $dst_h == "*") $mlt=1;

	#### Calculate new dimensions
	$img_new_w =  round($src_w * $mlt);
	$img_new_h =  round($src_h * $mlt);
	return array("w" => $img_new_w, "h" => $img_new_h, "mlt_w"=>$mlt_w, "mlt_h"=>$mlt_h,  "mlt"=>$mlt);
}

function img_get_resized($img_original,$img_w,$img_h,$img_new_w,$img_new_h,$use_imagecreatetruecolor=false, $use_imagecopyresampled=false){

	//$img_original, -- image to be resized
	//$img_w, -- its width
	//$img_h, -- its height
	//$img_new_w, -- resized width
	//$img_new_h -- height
	//$use_imagecreatetruecolor, $use_imagecopyresampled allow use of these function 
	//if they exist on the server

	if( $use_imagecreatetruecolor && function_exists("imagecreatetruecolor")){
//		echo("Using ImageCreateTruecolor (better quality)<br>");
		$img_resized = imagecreatetruecolor($img_new_w,$img_new_h) or die("<br><font color=\"red\"><b>Failed to create destination image.</b></font><br>"); 
	} else {
//		echo("Using ImageCreate (usual quality)<br>");
		$img_resized = imagecreate($img_new_w,$img_new_h) or die("<br><font color=\"red\"><b>Failed to create destination image.</b></font><br>"); 

	}
	if($use_imagecopyresampled && function_exists("imagecopyresampled")){
//		echo("Using ImageCopyResampled (better quality)<br>");
		imagecopyresampled($img_resized, $img_original, 0, 0, 0, 0,$img_new_w, $img_new_h, $img_w,$img_h) or die("<br><font color=\"red\"><b>Failed to resize @ ImageCopyResampled()</b></font><br>"); 

	}else{
//		echo("Using ImageCopyResized (usual quality)<br>");
		imagecopyresized($img_resized, $img_original, 0, 0, 0, 0,$img_new_w, $img_new_h, $img_w,$img_h) or die("<br><font color=\"red\"><b>Failed to resize @ ImageCopyResized()</b></font><br>"); 
	}
	return $img_resized;
}

function make_filename($image_name){
	global $HTTP_POST_VARS;
	## creates unique name, here I assume that it will never happen that in same second 
	## two files with same name on user's site will be uploaded. However you can use your
	## ways to generate unique name. Function unqueid() for example.

	$file_name = time()."_$image_name";  		
	#kick the original extension
	$pos = strrpos($file_name, '.');
	//personally I think jpeg rulez so I hardoce its extension here
	$file_name = substr($file_name, 0,$pos).".jpg";


	

	$file_name	= $HTTP_POST_VARS["img_name"].".jpg";

	return $file_name;
}

?>


Bastien

Cat, the other other white meat
 
OR you could use something like this:

if u'r using a submit-pic form consider this in the submit page
Code:
<?
 if ($_FILES['file_to_upload']) {

  if (move_uploaded_file($_FILES['file_to_upload']['tmp_name'], "./path/to/dir/file.jpg")) {
           ## do stuff
  }
  }
?>

then i use this code to resize pics (u need GD)
Code:
$max_width_height = "100"; # max size of thumb in pixels

$size = getimagesize("./path/to/dir/file.jpg");
if ($size[0] > $size[1]) { $bigside = $size[0]; } else {  $bigside = $size[1]; }
$ratio = (($max_width_height * 100) / $bigside);
$new_width = $size[0] * ($ratio / 100);
$new_height = $size[1] * ($ratio / 100);

$original = imagecreatefromjpeg("./path/to/dir/file.jpg");
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($new, $original, 0, 0, 0, 0, $new_width, $new_height, $size[0], $size[1]);
imagejpeg($new, "./path/to/resized.jpg");
imagedestroy($new);
imagedestroy($original);


jamesp0tter,
jamespotter@netcabo.pt

p.s.: sorry for my (sometimes) bad english :p
 
I am interested in resizing my
image (max size 800x800 qual 70) in the /photos/ folder.
storing a thumb (max size 100x100) in the /photos/thumbs/ folder.
Then storing the location of both as well as a comment in my mySQL database.
$name, $img_location, $thumb_location

Here is what i already have. could someone //comment on anything they change so i can see what you added and took away? thanks

// CONFIG
$serverpath = "/home/LOCALHOST/public_html/photos"; // Path to where images should be uploaded to on the server.
$urltoimages = " // Web address to where the images are accessible from.
$maxsize = "250000"; // Example - 20000 is the same as 20kb
$mode = $_GET['mode'];
if ($mode == "") { $mode = "form"; }

if ($mode == "form") {
echo "<form enctype='multipart/form-data' method='post' action='?mode=upload'>\n";
echo "<input name='img_name' type='text' id='img_name' value='title your image'>\n";
echo "<input type='file' name='file'>\n";
echo "<input type='submit' name='Submit' value='Go'>\n";
}


if ($mode == "upload") {

$file = $_FILES['file']['name'];
// If you add your own file types don't forget to add an uppercase version.
$allowedfiles[] = "gif";
$allowedfiles[] = "jpg";
$allowedfiles[] = "jpeg";
$allowedfiles[] = "png";
$allowedfiles[] = "GIF";
$allowedfiles[] = "JPG";
$allowedfiles[] = "JPEG";
$allowedfiles[] = "PNG";

if($_FILES['file']['size'] > $maxsize)
{
print "File size is too big - please reduce file size and try again.";
}
else {
$path = "$serverpath/$file";
$path2 = "$urltoimages/$file";
foreach($allowedfiles as $allowedfile) {

if ($done <> "yes") {
if (file_exists($path)) {
echo "A file with this name already exists - please rename the file and reupload.";
exit;
}
}

if (substr($file, -3) == $allowedfile) {
move_uploaded_file($_FILES['file']['tmp_name'], "$path");
$done = "yes";
// Insert database
require "header.php";
db_connect();

$form_name = urldecode($_POST['img_name']);
$form_img_location = urldecode($path2);

$sql="INSERT INTO photos (name, img_location)
VALUES ('$form_name','$form_img_location')";
$result = mysql_query($sql)
or die ('I cannot query database: ' . mysql_error());
// end database code
echo "<p>Your image has been successfully uploaded to our server and can be accessed using the URL provided below.</p>";
echo "<p><A href='$urltoimages/$file' target='_blank'><strong>$urltoimages/$file</strong></a></p>";
echo "<p><img src='$urltoimages/$file' border='0'>";
}

}

if ($done <> "yes") { print "<p><b>Error:</b> Your image as not been uploaded becuase it is not a recognised image file. Please try again.</p>"; }
}
}
//End Code
 
people read old threads? or should i start my own?

--i3iz
Technical Newbie
 
what part works and what part dosen't?

Sera
I often believe that...
My computer is possessed!
 
Sera- Thanks for the reply. It all works, i just dont know how to get it to shrink the images. Right now it says if your image is over 250K then "file is too large" I would rather if the file is over 250Kb resize to max 800x800 75Qual. I am pretty sure this is do-able but i really dont get the $_file variable, i am new to php and it appears to act as an array or something that i have 0 experience with. So i am asking that someone can put some comments and insert some code to get it to rename. seems like it should be like 15 lines of code or so.
Thanks for your concern.

--i3iz
Technical Newbie
 
Try:
print_r($_FILES);
This will show you the content and structure of the $_FILES variable.

As for resizing I'm not that much help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top