PHP – Hello :) https://blog.samyapp.com Wed, 20 Apr 2016 09:04:51 +0000 en-US hourly 1 https://wordpress.org/?v=4.8.7 102402223 Extract images from a zip archive https://blog.samyapp.com/extract-images-from-a-zip-archive/ https://blog.samyapp.com/extract-images-from-a-zip-archive/#respond Wed, 17 Sep 2008 16:26:25 +0000 https://blog.samyapp.com/?p=137 For my second example of using my image thumbnailer I’ve thrown together a little script which accepts a zip archive upload containing images and generates and returns to the browser a new zip archive containing a thumbnail for each image in the original. Source code download at the end of this page. zip2thumb.php [crayon-5bf33185924d4846489441/] Download […]

The post Extract images from a zip archive appeared first on Hello :).

]]>
For my second example of using my image thumbnailer I’ve thrown together a little script which accepts a zip archive upload containing images and generates and returns to the browser a new zip archive containing a thumbnail for each image in the original.

Form to upload a zip file containing images

Form to upload a zip file containing images

After processing a new zip is sent to the browser containing thumbnails

After processing a new zip is sent to the browser containing thumbnails


Source code download at the end of this page.

zip2thumb.php

<?php
require_once dirname(__FILE__) . '/paGdThumbnail.php';

$thumb_width = 150;
$thumb_height = 150;
$thumb_quality = 75;
$thumb_method = 'crop';
$thumb_bgColour = array(0,0,0);

// give us lots of time
set_time_limit(0);

// use to store error messages in.
$error = '';

$errors = array(
	UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
	UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
	UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
	UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
	UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
	UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
	UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.'
);

// get url to link to thumbs
$pathinfo = pathinfo($_SERVER['SCRIPT_NAME']);
$download_url = 'http://'.$_SERVER['HTTP_HOST'] . '/' . $pathinfo['dirname'] . '/thumbs.zip';

// has the form been submitted?
if( isset($_POST['submit']) ){

	// was a file submitted?
	if( isset($_FILES['zip']) ){
		// any errors?
		if( !$_FILES['zip']['error'] ){
			// security check
			if( is_uploaded_file($_FILES['zip']['tmp_name']) ){
				// is it a zip file?
				if( preg_match('#.zip$#i', $_FILES['zip']['name']) ){

					// get the thumbnail options from the form
					$thumb_width = (int)$_POST['thumb_width'];
					$thumb_height = (int)$_POST['thumb_height'];
					$thumb_method = $_POST['thumb_method'];

					// create a zip archive object
					$zip = new ZipArchive();
					if( $zip->open($_FILES['zip']['tmp_name']) ){
						$output_name = 'thumbs.zip';
						// create output archive
						$output = new ZipArchive();
						if( $output->open($output_name, ZipArchive::OVERWRITE ) ){

							// loop through all the files in the archive
							for( $i = 0; $i < $zip->numFiles; $i++){
								$entry = $zip->statIndex($i);
								// is it an image?	
								if( $entry['size'] > 0 && preg_match('#.(jpg|gif|png)$#i', $entry['name'] ) ){
									$file = $zip->getFromIndex($i);
									if( $file ){
										$image = imagecreatefromstring($file);
										if( $image ){
											$thumb = paGdThumbnail($image, $thumb_width, $thumb_height, $thumb_method, $thumb_bgColour);
											imagedestroy($image);
											if( $thumb ){
												ob_start();
												imagejpeg($thumb,null,$thumb_quality);
												imagedestroy($thumb);
												$thumb_data = ob_get_clean();
												$output->addFromString(preg_replace('#.(jpg|gif|png)$#i', '_t.jpg', $entry['name']), $thumb_data);
											}
										}
									}
								}
							}
							$output->close();
						}
						$zip->close();
						header("Location: $download_url");
						exit();
					}
				}
				else{

				}
			}
		}
		// display an error message
		else{
			$error = $errors[$_FILES['zip']['error']];
		}

	}

}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Zip to Thumbnails :p</title>
</head>
<body>
	<h2>Upload a zip archive containing images in jpeg, png or gif format.</h2>
	<p>You will receive a zip archive containing a thumbnail for each image in the original archive.</p>
	<p>Select the thumbnail width, height and method using the form below.</p>
<?php if( $error ){ ?>
	<h3 style="color: red;"><?php echo $error?></h3>
<?php } ?>
	<form action="<?php echo $_SERVER['SCRIPT_NAME']?>" method="post" enctype="multipart/form-data">
		<input type="file" name="zip" />
		Width: <input type="text" name="thumb_width" value="<?php echo $thumb_width?>" size="4" />
		Height: <input type="text" name="thumb_width" value="<?php echo $thumb_width?>" size="4" />
		<select name="thumb_method">
			<option value="crop">Crop</option>
			<option value="scale"<?php if( $thumb_method == 'scale' ) echo ' selected="selected" '?>>Scale</option>
		</select>
		<input type="submit" name="submit" value="Create Thumbnails" />
	</form>
</body>
</html>

Download from GitHub.

The post Extract images from a zip archive appeared first on Hello :).

]]>
https://blog.samyapp.com/extract-images-from-a-zip-archive/feed/ 0 137
Create thumbnails for all images in a directory https://blog.samyapp.com/create-thumbnails-for-all-images-in-a-directory/ https://blog.samyapp.com/create-thumbnails-for-all-images-in-a-directory/#comments Wed, 17 Sep 2008 16:24:53 +0000 https://blog.samyapp.com/?p=134 This is a simple script to demonstrate using my image resizing function . It scans the directory you place it in for any images, generates a thumbnail for each image, then outputs html to display the thumbnails as links to each image. It requires php 5.1+ as it uses the Directory Iterator to get the […]

The post Create thumbnails for all images in a directory appeared first on Hello :).

]]>
This is a simple script to demonstrate using my image resizing function
. It scans the directory you place it in for any images, generates a thumbnail for each image, then outputs html to display the thumbnails as links to each image.

It requires php 5.1+ as it uses the Directory Iterator to get the files in the directory. If you’d like to see a version compatible with earlier versions of php leave a comment below.

For each file it checks that:

  1. It is a jpeg, png or gif image (or at least has that file extension)
  2. The filename doesn’t end in "_t.jpg" (as this is what is uses for naming the thumbnails)


Download from GitHub.
It then checks if a thumbnail exists with the same name and if one doesn’t (or the image file has been modified more recently) it attempts to create a thumbnail and save it in the current directory with the same name as the image, but with "_t.jpg" at the end of the name.

It pretty simple and meant more as an example for the resizing function, but would be quite easy to extend to show the image in the page with links to the previous and next image for example.

The code below needs the image resizing function to work which needs to be in the same directory. You can copy and paste or download both in a zip.

index.php

<?php

// thumbnail configuration
$thumb_width = 75;
$thumb_height = 75;
$thumb_method = 'crop';
$thumb_bgColour = null;//array(255,255,240);
$thumb_quality = 60;

// Let script run for as long as it needs to when creating thumbnails.
// Some web hosts won't let you use this function. In that case you'll need
// to comment it out and just refresh the script until it has thumbnailed all the images.
set_time_limit(0);

// include the thumbnail function
require_once dirname(__FILE__) . '/paGdThumbnail.php';

// get the path to the current directory
$path = dirname(__FILE__);

// get the url for the images
$path_info = pathinfo($_SERVER['SCRIPT_NAME']);
$url = $path_info['dirname'];

// create an array to store image names in.
$images = array();

$dir = new DirectoryIterator($path);

/*
 Loop through the directory, finding all images that aren't thumbnails.
 For each image:
	- if it doesn't already have a thumbnail, or the thumbnail is older than the image,
		create a thumbnail.
	- get info about the image
	- add the image to our images array
*/
foreach( $dir as $entry ){
	if( $entry->isFile() ){
		if( preg_match('#^(.+?)(_t)?.(jpg|gif|png)#i', $entry->getFilename(), $matches) ){

			list( ,$name, $is_a_thumb, $extension) = $matches;

			// if its not a thumbnail
			if( !$is_a_thumb ){
				// does a valid thumbnail exist?
				$has_thumb = false;
				$thumb_file = $path . '/' . $matches[1] . '_t.jpg';
				if( file_exists($thumb_file) && filemtime($thumb_file) > filemtime($entry->getPathname()) ){
					$has_thumb = true;
				}
				else{
					// no thumbnail, so we shall create one!

					// create a gd image. reading the contents of the image file into a string, then
					// using imagecreatefromstring saves having to check the filetype and which 
					// imagecreatefrom(jpeg/gif/png) function to use
					$image = imagecreatefromstring(file_get_contents($entry->getPathname()));

					if( $image ){
						// create the thumbnail
						$thumb = paGdThumbnail($image, $thumb_width, $thumb_height, $thumb_method, $thumb_bgColour);
						// free the image resource
						imagedestroy($image);
						if( $thumb ){
							// save the thumbnail
							if( imagejpeg($thumb, $thumb_file, $thumb_quality) ){
								$has_thumb = true;
							}
							// free the memory used by the thumbnail image
							imagedestroy($thumb);
						}
					}
				}
				if( $has_thumb ){
					$images[$entry->getFilename()] = $name;
				}
			}
		}
	}
}

// sort the images array so always in the same order
ksort($images);

// end or processing, now display the gallery
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Thumbnails :p</title>
<style type="text/css">
<!--
#thumbs{
	position: relative;
}

#thumbs div{
	float: left;
	width: <?php echo $thumb_width + 30?>px;
	height: <?php echo $thumb_height + 30?>px;
	text-align: center;
}

#thumbs a:link img, #thumbs a:visited img{
	border: 1px solid #acacac;
	padding: 5px;
}

#thumbs a:hover img{
	border: 1px solid black;
}

-->
</style>
</head>
<body>
<div id="thumbs">
<?php foreach( $images as $imagename => $name ){ ?>

	<div>
		<a href="<?php echo $url . '/' . $imagename?>" title="Full Size"><img src="<?php echo $url . '/' . $name . '_t.jpg'?>"  /></a>
	</div>

<?php }?>
</div>
<div id="pb">
	powered by <a href="https://blog.samyapp.com/">a simple php image thumbnail script</a>
</div>
</body>
</html>

The post Create thumbnails for all images in a directory appeared first on Hello :).

]]>
https://blog.samyapp.com/create-thumbnails-for-all-images-in-a-directory/feed/ 2 134
Image Resizing with php https://blog.samyapp.com/image-resizing-with-php/ https://blog.samyapp.com/image-resizing-with-php/#respond Wed, 17 Sep 2008 16:23:58 +0000 https://blog.samyapp.com/?p=131 One of the great things about php is its built in support for the gd image library which makes creating thumbnails from images quite trivial, although you still need to calculate the correct dimensions if you want your thumbs to be resized proportionally. Here’s a function that takes a gd image, a maximum width and […]

The post Image Resizing with php appeared first on Hello :).

]]>
One of the great things about php is its built in support for the gd image library which makes creating thumbnails from images quite trivial, although you still need to calculate the correct dimensions if you want your thumbs to be resized proportionally.

Here’s a function that takes a gd image, a maximum width and / or maximum height and returns a new thumbnail image that fits into these sizes. The function can either scale the image proportionally so the whole image fits completely into the new size, or scale and crop the original so that the thumbnail is exactly the maximum width and height.


Download from GitHub.

If either the maximum width or maximum height is 0 or null then the function calculates these proportionally which is useful if you want all thumbnails a certain width and height and don’t care about the other dimension.

You can also specify an rgb background colour which will force the thumbnail to be exactly $max_width x $max_height with any space at the left and right (or top and bottom depending on whether the source image is portrait or landscape) filled in with the background colour.

I’ve written a couple of scripts to show usage of this function below – one creates thumbnails for every image in the same directory as the script, then generates html to show these. The other extracts images from a zip archive through a standard form upload and creates and returns a zip archive containing generated thumbnails.

You can copy and paste the code, or download the zip file containing all three scripts.

paGdThumbnail.php

<?php

function paGdThumbnail($image, $max_width, $max_height, $method = 'scale', $bgColour = null)
{
	// get the current dimensions of the image
	$src_width = imagesx($image);
	$src_height = imagesy($image);

	// if either max_width or max_height are 0 or null then calculate it proportionally
	if( !$max_width ){
		$max_width = $src_width / ($src_height / $max_height);
	}
	elseif( !$max_height ){
		$max_height = $src_height / ($src_width / $max_width);
	}

	// initialize some variables
	$thumb_x = $thumb_y = 0;	// offset into thumbination image

	// if scaling the image calculate the dest width and height
	$dx = $src_width / $max_width;
	$dy = $src_height / $max_height;
	if( $method == 'scale' ){
		$d = max($dx,$dy);
	}
	// otherwise assume cropping image
	else{
		$d = min($dx, $dy);
	}
	$new_width = $src_width / $d;
	$new_height = $src_height / $d;
	// sanity check to make sure neither is zero
	$new_width = max(1,$new_width);
	$new_height = max(1,$new_height);

	$thumb_width = min($max_width, $new_width);
	$thumb_height = min($max_height, $new_height);

	// if bgColour is an array of rgb values, then we will always create a thumbnail image of exactly
	// max_width x max_height
	if( is_array($bgColour) ){
		$thumb_width = $max_width;
		$thumb_height = $max_height;
		$thumb_x = ($thumb_width - $new_width) / 2;
		$thumb_y = ($thumb_height - $new_height) / 2;
	}
	else{
		$thumb_x = ($thumb_width - $new_width) / 2;
		$thumb_y = ($thumb_height - $new_height) / 2;
	}

	// create a new image to hold the thumbnail
	$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
	if( is_array($bgColour) ){
		$bg = imagecolorallocate($thumb, $bgColour[0], $bgColour[1], $bgColour[2]);
		imagefill($thumb,0,0,$bg);
	}

	// copy from the source to the thumbnail
	imagecopyresampled($thumb, $image, $thumb_x, $thumb_y, 0, 0, $new_width, $new_height, $src_width, $src_height);
	return $thumb;
}

The post Image Resizing with php appeared first on Hello :).

]]>
https://blog.samyapp.com/image-resizing-with-php/feed/ 0 131