photo resize question

Currently, through an admin cp, when photos are uploaded, they are sized into 3 different sizes.
We were wondering if it was possible to have a function that would just change the size of the main (‘big’) image, possibly by a percentage, to scale it down to the thumbnail size.
Right now, all of the thumbnails are sized to 120x120. If we could just have the original shrunk, they would be constrained properly.

Im not sure if this is possible?
appreciate any help!

Very very easy. There are TONS of image code built into PHP…

Here is a link with all the details, no need to duplicate it here. (It has been posted here somewhere!)

Look at the example #1 and #2, both will explain and with what you want to do. (Easy and work fast!)

http://php.net/manual/en/function.imagecopyresampled.php

Good luck… (Post back if it does or doesn’t work for you…)

Hi Ernie, thanks for your reply…

Very very easy, says you, ???..But i currently don’t speak PHP, so not quite sure how it works…
The articles you linked do seem to be what I’m going for, just not sure how to apply them to what is currently there.

Thank you for the help!

Well, I will send you code, but, I have not seen any of your code as yet. At least give some explanation of what you want. You mentioned a large main image, but, then said they are all 120x120. This is not large.

I do not know what you want… I can give you an example of a general resize function if you wish, but, they are on the example I sent you already. That was an entire routine to shrink any picture by a percentage.
If you want to shrink an input picture to size 120x120, that is easy too.

So, more info, code is not needed if you just have some idea of what you want the new code to do…
Let us know…

The images on this page: http://harmonyhall.com/Gallery/artists.php
all go into an individual artists page, which will display one “main” image, and maybe 2 or 3 thumbnails of the other paintings, that when clicked on, will show their bigger image. Some of these images are landscape some portrait. We wanted the thumbs to be constrained properly, based on their biggest image. Right now, they are all uploaded with a set size.

Well, I can give you code, but, let me ask one further question first.

Are you trying to load a lot of thumbnails at one time? Normally, a picture in a folder is okay a few ‘k’.
So, if you show a dozen thumbs, you are talking about only, maybe 120k of data. I would not actually
create thumbnails, just resize them onscreen. Did that make sense?

So, the images are normally displayed with an image tag. These can use the width and height arguments.
You can set the size of them to a set size, such as 120x120 or with percentages such as "10%“x"10%”.
That way, you do not have to resize the pictures. But, sometimes you still want to resize them if you are
planning to load a very large number of thumbs on one page. (Perhaps for an ADMIN page.)

Well, sorry for being off-center on your request, I just want to be clear what you need for the code.
If it is a resizing function that checks current size and figures out a set size based on a max height or
width, that is possible with the sample I gave you. I can rewrite it to your needs. Not hard.

If only 2 or 3 thumbnails, I would just use the tags with and height arguments with percentages
instead of actual pixels… Well, let me know what I can do. Either way it is not too hard to do…

a good example would be on this page:
http://harmonyhall.com/Gallery/artist/artist.php?id=20&work_id=55

The big image you see is landscape, right?
Then you have 3 thumbs under it. The first from the left being landscape. But as you can tell the image is cropped to 120 x 120, as opposed to just shrinking the bigger of this image to maybe 120 x 105, which would keep the proportion of the original image, just smaller.

Well, you have some PHP code which pull these four from the database and writes four HREF’s for you.
One is full-size, plus 3 that are smaller. In the PHP code, you would have to get the size of the picture
and set up the thumbnail to display it at a new size. The code would be complicated, but, not too long.
So, you display the pix at 100% x 100% in the top picture. If you want a max of 120 pixels wide for the
thumbnail, you would use something like this:
$widthpercent = $picturewidth / 120;
$newwidth = 120;
$newheight = $pictureheight * $newwidth;

So, what this would do is resize the width only to the 120 max and the correct height.
You would have to see if the picture is in landscape or portrait first. Something like this:
if($picturewidth > $pictureheight){
// handle picture as landscape…
}else{
// handle picture as portrait…
}

Hope that makes sense, if you need actual code, then show what you have now for how the picture is placed into the HREF’s.

why complicated?
do i need to specify a max width?
And is doing this possible within the code i have already?
thank you!

sorry, meant to paste this code. Think this is what your looking for, not sure:

<?php if (sizeof($works) > 1) { ?>
<div class="morework">
	<div class="nlp">CLICK BELOW TO VIEW LARGER IMAGE</div>
</div>
<table width="380" border="0" cellpadding="0" cellspacing="0">
	<tr>
		<?php foreach($works as $w) { ?>
			<?php if ($w['id'] != $main_work['id']) { ?>
				<?php $more_link = $_SERVER['PHP_SELF']."?id=$id&amp;work_id={$w['id']}" ?>
				<td width="130" valign="top">    
					<div class="td">
						<a href="<?php echo $more_link; ?>">
							<img src="../../uploads/works/<?php echo $w['id']; ?>/square_thumb_120_<?php echo $w['filename']; ?>"  alt="sign" border="0" vspace="0" hspace="0">
						</a><br />
						<?php echo escaporize($w['title']); ?>
	        			<p><a class="button" href="<?php echo $more_link; ?>">Click here</a></p>
	            	</div>
				</td>
				<td width="10" valign="top" ></td>
			<?php } ?>
		<?php } ?>
		
		
	</tr>
</table>

Well, complicated, because I did not write your code. You have to resize the display to fit the size you want or you have to resize the thumbnail to match the display.

This code you posted:

sign
Turns into something like this in "live" code:
← back
So, the picture is loaded from a .PNG that is stored in a folder "images". How, or when or where was this .PNG file resized to the 120x120 or whatever. I do not see that code. I gave you sample code to reisize pictures and to resize them depending on landscape or portrait.

So, yes, it is possible. But, I don’t know about your code. You showed how the thumbnails are displayed, but, not how they are created. If you mean that you want to resize all of your thumbnails, then you would need the originals and have to recreate the thumbnails you have now.
Not really sure what you need. Please give me another hint… Thanks!

maybe i did not supply you with the proper code. i got what i posted from the
Gallery/artist/artist.php file, where i saw the thumb info, so figured that was the code.
What is the ping image you posted? It appears all of the artists are referenced by a number id, so the code would have to reflect each artists own pictures and decide how to resize them based off the bigger size, yes?

this is the code from the works.php file:

<?php require('_bootstrap.inc.php'); function save_image_with_thumbs($id) { // Create a directory with the ID of the entry. if(!file_exists('uploads/works/'.$id)) { if(!mkdir('uploads/works/'.$id)) { die('Impossible to create dir '.'uploads/works/'.$id); } } // Save the original file to it, and thumbnail. $unique_name = md5(mktime().$_FILES['image_file']['name']).'.jpg'; $f = "uploads/works/$id/$unique_name"; if(!move_uploaded_file($_FILES['image_file']['tmp_name'], $f)) { die('Impossible to save file '.$f); } if (!resize_image($f, "uploads/works/$id/thumb_60_$unique_name")) { die('Impossible to save thumbnail for '.$f); } if (!resize_image($f, "uploads/works/$id/large_380_$unique_name", 380, 380)) { die('Impossible to save large image for '.$f); } if (!resize_and_crop($f, "uploads/works/$id/square_thumb_120_$unique_name", 120)) { die('Impossible to save cropped thumbnail for '.$f); } if (!resize_and_crop($f, "uploads/works/$id/square_thumb_149_$unique_name")) { die('Impossible to save cropped thumbnail for '.$f); } // Save the filename to the DB. if(!update_row_in_db('works', array('filename'=>$unique_name, 'id'=>$id))) { die('Impossible to save filename to DB'); } } switch ($_REQUEST['_action']) { case 'new': $artists = stripslashes_r(mysql_fetch_all("SELECT * FROM artists ORDER BY last_name")); $next_action = 'create'; include('views/admin/header.inc.php'); include('views/admin/new_work.inc.php'); include('views/admin/footer.inc.php'); break; case 'edit': if (is_numeric($_GET['id'])) { $id = (int) $_GET['id']; } $artists = stripslashes_r(mysql_fetch_all("SELECT * FROM artists ORDER BY last_name")); $work = stripslashes_r(mysql_fetch_one("SELECT * FROM works WHERE id = $id")); $next_action = 'update'; include('views/admin/header.inc.php'); include('views/admin/edit_work.inc.php'); include('views/admin/footer.inc.php'); break; case 'update': if (update_row_in_db('works', $_REQUEST['work'])){ // Take care of the uploaded file. if ($_FILES['image_file']['name']) { // Create a directory with the ID of the entry. if (is_numeric($_POST['work']['id'])) { $id = (int) $_POST['work']['id']; } else { die('ID is missing or non numeric.'); } save_image_with_thumbs($id); $flash = "The item was correctly updated."; } else { $flash = "The item was correctly updated, and the image left untouched."; } } else { $flash = "The item was not correctly updated"; } $works = stripslashes_r(mysql_fetch_all("SELECT a.last_name, a.first_name, w.* FROM works w LEFT JOIN artists a ON w.artist_id = a.id ORDER BY a.last_name, w.id")); include('views/admin/header.inc.php'); include('views/admin/list_works.inc.php'); include('views/admin/footer.inc.php'); break; case 'create': if (insert_row_in_db('works', $_POST['work'])){ // Take care of the uploaded file. if ($_FILES['image_file']['name']) { // Create a directory with the ID of the entry. $id = mysql_insert_id(); save_image_with_thumbs($id); $flash = "The item was correctly created"; } else { $flash = "The item was correctly created, but the image was missing."; } } else { $flash = "The item was not correctly created"; } $works = stripslashes_r(mysql_fetch_all("SELECT a.last_name, a.first_name, w.* FROM works w LEFT JOIN artists a ON w.artist_id = a.id ORDER BY a.last_name, w.id")); include('views/admin/header.inc.php'); include('views/admin/list_works.inc.php'); include('views/admin/footer.inc.php'); break; case 'delete': if (is_numeric($_GET['id'])) { $id = (int) $_GET['id']; } if(!mysql_query("DELETE FROM works WHERE id = $id")) { die("Impossible to delete the work."); } else { $flash = "The entry was correctly deleted."; } $works = stripslashes_r(mysql_fetch_all("SELECT a.last_name, a.first_name, w.* FROM works w LEFT JOIN artists a ON w.artist_id = a.id ORDER BY a.last_name, w.id")); include('views/admin/header.inc.php'); include('views/admin/list_works.inc.php'); include('views/admin/footer.inc.php'); break; default: # we list the items. $works = stripslashes_r(mysql_fetch_all("SELECT a.last_name, a.first_name, w.* FROM works w LEFT JOIN artists a ON w.artist_id = a.id ORDER BY a.last_name, w.id")); include('views/admin/header.inc.php'); include('views/admin/list_works.inc.php'); include('views/admin/footer.inc.php'); break; } ?>

Thanks for listing your code. Please place it inside the PHP tags above next time as it is easier to copy and view that way… So, this part of the last posted code:
[php]
// Save the original file to it, and thumbnail.
$unique_name = md5(mktime().$FILES[‘image_file’][‘name’]).’.jpg’;
$f = “uploads/works/$id/$unique_name”;
if(!move_uploaded_file($FILES[‘image_file’][‘tmp_name’], $f)) {
die('Impossible to save file '.$f);
}
if (!resize_image($f, "uploads/works/$id/thumb_60
$unique_name")) {
die('Impossible to save thumbnail for '.$f);
}
if (!resize_image($f, "uploads/works/$id/large_380
$unique_name", 380, 380)) {
die('Impossible to save large image for '.$f);
}

if (!resize_and_crop($f, “uploads/works/$id/square_thumb_120_$unique_name”, 120)) {
die('Impossible to save cropped thumbnail for '.$f);
}
if (!resize_and_crop($f, “uploads/works/$id/square_thumb_149_$unique_name”)) {
die('Impossible to save cropped thumbnail for '.$f);
}

// Save the filename to the DB.
if(!update_row_in_db(‘works’, array(‘filename’=>$unique_name, ‘id’=>$id))) {
die(‘Impossible to save filename to DB’);
}
}
[/php]
Shows that this is where a few different versions of the files are saved. But, it uses a function called
“resize_image” and another called “resize_and_crop”. These are your actual resizing function codes that
we would need to see. These can be altered to fix the error in the resizing. Can you please locate these
and post them, each in side different PHP tags for us. Then, we can get you set up with new versions.
(PS: Both of these functions will be in an include file or earlier in the code you posted and will start with
something like “function resize_image($variable1, $variable2){” ) Thanks…

i dont even know where to begin looking for those files…i will begin my search.
thank you for helping me.

Im assuming its not this, but going to ask anyways to rule it out.

<?php require('_bootstrap.inc.php'); function save_image_with_thumbs($id) { // Create a directory with the ID of the entry. if(!file_exists('uploads/works/'.$id)) { if(!mkdir('uploads/works/'.$id)) { die('Impossible to create dir '.'uploads/works/'.$id); }

Nope, but, it might be inside that include: require(’_bootstrap.inc.php’);
So, look in that bootstrap.inc.php and see if those two functions are in that file…

What is the bootstrap files purpose?
bootstrap file contains:

<?php // Custom installation of Pear, because it's not on the server. ini_set('include_path', realpath('../_pear') . PATH_SEPARATOR . ini_get('include_path')); require_once('_config.inc.php'); require_once('_lib.inc.php'); // We are escaping user inputed data ourselves, always. if (get_magic_quotes_gpc()) { $_POST = array_map('stripslashes_r', $_POST); $_GET = array_map('stripslashes_r', $_GET); $_COOKIE = array_map('stripslashes_r', $_COOKIE); $_REQUEST = array_map('stripslashes_r', $_REQUEST); } // We'll always use the DB, so open connection. connect_to_db(); ?>

LINE 123?

<?php function connect_to_db() { global $config; global $db_connection; if (!isset($db_connection)) { $db_connection = mysql_connect($config['db_host'], $config['db_user'], $config['db_pass']) or die("Impossible to open a connection to the database.".mysql_error()); if(function_exists('mysql_set_charset')) { mysql_set_charset('utf8'); } mysql_query('SET NAMES "UTF8"'); mysql_select_db($config['db_name']) or die("Impossible to open the given database : ". $config['db_name']); } } function stripslashes_r($value) { $value = is_array($value) ? array_map('stripslashes_r', $value) : stripslashes($value); return $value; } function addslashes_r($value) { $value = is_array($value) ? array_map('addslashes_r', $value) : addslashes($value); return $value; } function magicaddslashes($t) { return (get_magic_quotes_gpc()==1) ? $t : addslashes($t); } function escaporize($thing, $quotes = ENT_QUOTES, $charset = 'UTF-8') { if (is_array($thing)) { $escaped = array(); foreach ($thing as $key => $value) { $escaped[$key] = escaporize($value, $quotes, $charset); } return $escaped; } else { return htmlspecialchars($thing, $quotes, $charset); } } function mysql_fetch_all($sql) { $res = mysql_query($sql); if ($res) { $num = mysql_num_rows($res); $arr = array(); for($i=0; $i<$num; $i++) { $arr[] = mysql_fetch_assoc($res); } return $arr; } return false; } function mysql_fetch_one($sql) { $res = mysql_query($sql); if ($res) { return mysql_fetch_assoc($res); } return false; } function trace_start_file() { echo ""; } function trace_end_file() { echo ""; } function update_row_in_db($table_name, $data) { $data = addslashes_r($data); // Build the query. $q = "UPDATE $table_name SET "; foreach ($data as $key => $value) { if ($key != 'id' && $key != 'image_file') { $q .= "`$key` = '$value',"; } } $q = rtrim($q, ','); // trimming trailing comma. $q .= " WHERE id = {$data['id']}"; return mysql_query($q) or die(mysql_error().$q); } function insert_row_in_db($table_name, $data) { $data = addslashes_r($data); // Build the query. $q = "INSERT INTO $table_name ("; foreach ($data as $key => $value) { if ($key != 'id' && $key != 'image_file') { $q .= "`$key`,"; } } $q = rtrim($q, ','); // trimming trailing comma. $q .= ") VALUES ("; foreach ($data as $key => $value) { if ($key != 'id' && $key != 'image_file') { $q .= "'$value',"; } } $q = rtrim($q, ','); $q .= ")"; return mysql_query($q) or die(mysql_error().$q); } function resize_image($source, $dest, $max_width=60, $max_height=60) { $source_quality = 80; $src_img = ImageCreateFromJpeg($source); $orig_x = ImageSX($src_img); $orig_y = ImageSY($src_img); $new_y = $max_height; $new_x = $orig_x / ($orig_y / $max_height); if ($new_x > $max_width) { $new_x = $max_width; $new_y = $orig_y / ($orig_x / $max_width); } $dst_img = ImageCreateTrueColor($new_x,$new_y); ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $new_x, $new_y, $orig_x, $orig_y); $result = ImageJpeg($dst_img, $dest, $source_quality); ImageDestroy($src_img); ImageDestroy($dst_img); return $result; } function resize_and_crop($source_file, $dest_file, $dest_side = 149) { // Resize and crop an image to a square image that is *filled* with // the source image. require_once 'Image/Transform.php'; $im = Image_Transform::factory('GD'); $im->load($source_file); if ($im->getImageWidth() > $im->getImageHeight()) { // L'image d'origine est horizontale. $im->scaleByY($dest_side ); // scale proportionally the image so the height = 190. $im->crop($dest_side , $dest_side , ($im->new_x - $dest_side ) / 2, 0); } else { // L'image d'origine est verticale. $im->scaleByX($dest_side ); // scale proportionally the image so the width = 190. $im->crop($dest_side , $dest_side , 0, ($im->new_y - $dest_side ) / 2); } $im->save($dest_file); $im->free(); return true; } # PHP Calendar (version 2.3), written by Keith Devens # http://keithdevens.com/software/php_calendar # see example at http://keithdevens.com/weblog # License: http://keithdevens.com/software/license function generate_calendar($cottage, $year, $month, $pn = array(), $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0){ $not_before = "$year-".str_pad($month, 2, "0", STR_PAD_LEFT)."-01"; $not_after = "$year-".str_pad($month, 2, "0", STR_PAD_LEFT)."-31"; $req = "SELECT * FROM reservations WHERE cottage = '$cottage' AND ((ends_on >= '$not_before' AND ends_on <= '$not_after') OR (starts_on >= '$not_before' AND starts_on <= '$not_after')) ORDER BY starts_on ASC"; $r = stripslashes_r(mysql_fetch_all($req)); $all_occupied_days = array(); foreach ($r as $resa) { $start = (int) date('Ymd', strtotime($resa['starts_on'])); $end = (int) date('Ymd', strtotime($resa['ends_on'])); //echo $start; for($j=$start; $j<=$end; $j++) { //echo "j = $j\n"; $all_occupied_days[] = $j; } } $all_occupied_days = array_unique($all_occupied_days); #array(substr($j, 0, 4), substr($j, 4, 2), substr($j, 6, 2)); for($i=1; $i<=31; $i++) { foreach($all_occupied_days as $o) { if ($year == substr($o, 0, 4) && $month == substr($o, 4, 2) && $i == substr($o, 6, 2)) { $relevant_occupied_days[] = $i; } } } #print_r($relevant_occupied_days); $days = array(); if (is_array($relevant_occupied_days)) { foreach($relevant_occupied_days as $v) { $days[$v] = array(NULL, 'occupied'); } } $first_of_month = gmmktime(0,0,0,$month,1,$year); #remember that mktime will automatically correct if invalid dates are entered # for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998 # this provides a built in "rounding" feature to generate_calendar() $day_names = array(); #generate all the day names according to the current locale for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) #January 4, 1970 was a Sunday $day_names[$n] = ucfirst(gmstrftime('%A',$t)); #%A means full textual day name list($month, $year, $month_name, $weekday) = explode(',',gmstrftime('%m,%Y,%B,%w',$first_of_month)); $weekday = ($weekday + 7 - $first_day) % 7; #adjust for $first_day $title = htmlentities(ucfirst($month_name)).' '.$year; #note that some locales don't capitalize month and day names #Begin calendar. Uses a real . See http://diveintomark.org/archives/2002/07/03 @list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable if($p) $p = ''.($pl ? ''.$p.'' : $p).' '; if($n) $n = ' '.($nl ? ''.$n.'' : $n).''; $calendar = ''."\n". ''.$p.($month_href ? ''.$title.'' : $title).$n."\n"; if($day_name_length){ #if the day names should be shown ($day_name_length > 0) #if day_name_length is >3, the full name of the day will be printed foreach($day_names as $d) $calendar .= ''; $calendar .= "\n"; } if($weekday > 0) $calendar .= ''; #initial 'empty' days for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++){ if($weekday == 7){ $weekday = 0; #start a new week $calendar .= "\n"; } if(isset($days[$day]) and is_array($days[$day])){ @list($link, $classes, $content) = $days[$day]; if(is_null($content)) $content = $day; $calendar .= '' : '>'). ($link ? ''.$content.'' : $content).''; } else $calendar .= ""; } if($weekday != 7) $calendar .= ''; #remaining "empty" days return $calendar."\n
'.htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d).'
 
$day 
\n"; } // A date input widget. // Input format : YYYY-MM-DD function date_input($name, $date=0) { // day - month - year setlocale(LC_TIME, "en_US"); if ($date == 0) { $date = date('Y-m-d'); } $cur_year = (int) substr($date, 0, 4); //$start_year = $cur_year - 5; $start_year = date('Y'); $end_year = $cur_year + 2; for ($i = $start_year; $i <= $end_year; $i++) { $sel = $i == $cur_year ? 'selected' : ''; $year_options .= "${i}\n"; } $cur_month = (int) substr($date, 5, 2); $months = array('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'); for ($i=1; $i <= 12; $i++) { $padded_month = str_pad($i, 2, '0', STR_PAD_LEFT); $sel = $padded_month == $cur_month ? 'selected' : ''; $month_options .= "{$months[$i-1]}\n"; } $cur_day = (int) substr($date, 8, 2); for ($i=1; $i <= 31; $i++) { $padded_day = str_pad($i, 2, '0', STR_PAD_LEFT); $sel = $padded_day == $cur_day ? 'selected' : ''; $day_options .= "${i}\n"; } $out = "${day_options} ${month_options} ${year_options}"; return $out; } // Concatenate the date that was submited using the date_input() widget. function get_inputed_date($name) { $day = $_REQUEST["${name}_d"]; $month = $_REQUEST["${name}_m"]; $year = $_REQUEST["${name}_y"]; return magicaddslashes("$year-$month-$day"); } ?>

I think it is just a way to hide a folder so it doesn’t show up in HTML anyway or on the address-line.
Going by that file, look inside the require_once(’_lib.inc.php’); file. _lib.inc.php…
The two picture functions may be in there!

If not, you most likely have a copy of the files locally. You could use Windows Explorer and search for the function names in SEARCH. We need to look at those two functions to be able to get further…

Sponsor our Newsletter | Privacy Policy | Terms of Service