Create thumbnails using PHP or manully add thumbnails? - php

I have a Folder called "Gallery" inside which i have created a folder for Thumbails called "Gallery-Thumbs", where i manually add thumbnails.
My question is whether it is better to manually add thumbnails or create thumbnails dynamically using "GD" or "ImageMagick".
Problems with adding Thumbnails manually
If i forget to add a thumbnail for photo the chain of the Gallery breaks
It is tedious to resize all the images for creating the thumbnails
So does using PHP ImageProcessing function add additional overhead in creating thumbnails or is the correct approach?
-- Updated for answering Queries
How you add images to the "gallery" folder?
Through Direct file upload
How those images and thumbnails are accessed?
I use glob to get list of files in respective folders
How do you (want to) map images to thumbnails?
For thumbnails i use imageName-thumb.jpg,
so they appear in the list in the same order as they are in main image folder

Use PHP to create thumbnails once and save them in a "thumbnails" directory with the same file names. Then use these now-ready-to-be-used thumbnails directly.

If your going with some Dynamic image processing tool then it will be little bit time consuming process, except that it will be a great technique.
If you are going with the manual process then:
Make thumbnail compulsory using some client side script
It depends on your image orientation

I create the thumbnails during upload and either save in a different directory with the same name or add th_ to the front of the filename.
You could also upload some code to generate all the thumbs again for the images you currently have in your gallery in case you have missed any.
You could also resize to different sizes at the same time, watermark or add other effects.
This is my gallery and I have a thumb and normal size; the thumb was sharpened on upload and the normal watermarked. Bother versions have a drop shadow and the resizing etc. was done with Imagemagick.
http://www.rubble.info/gallery/
If you check the file is there before displaying it and it is missing you can show a default image.
You can check out my website for lots of different things you can do with php and Imagemagick.

I highly recommend using GD with some sort of caching to keep the ones that don't change. There is, however, already a superb library for doing this. It's an absolute favourite of mine and gives you easy image compression and resizing just with a GET URL.
Try Smart Image Resizer by ShiftingPixel:
http://shiftingpixel.com/2008/03/03/smart-image-resizer/
You can, if you wish, use a website I made as a reference using its page source: http://www.eastwood-whelpton.co.uk/about/gallery.php
Nearly all images on this website use the Smart Image Resizer GD library.
I can also provide the PHP code I used if you wish for examples. This particular code automatically adds any images found in my gallery folder to this page.

As stated previously you need PHP 5 with GD support. If you have these then here is a very handy function to create thumbnails of a given dimensions and quality ($options) from every image in a given directory ($from_dir) and save them to another directory ($to_dir).
function make_thumbnails($from_dir,$to_dir, $options){
$files = scandir($from_dir);
$exclude = array('.','..','etc.');
foreach($files as $fi => $fv){
if(!in_array($fv,$exclude)){
$from_file = $from_dir.$fv;
$to_file = $target_dir.$fv;
list($img_width, $img_height,$img_type) = getimagesize($from_file);
$scale = min($options['max_width'] / $img_width,
$options['max_height'] / $img_height
);
$new_width = $img_width * $scale;
$new_height = $img_height * $scale;
$new_img = imagecreatetruecolor($new_width, $new_height);
$src_img = imagecreatefromjpeg($from_file);
$success = $src_img && imagecopyresampled(
$new_img,
$src_img,
0, 0, 0, 0,
$new_width,
$new_height,
$img_width,
$img_height
) && imagejpeg($new_img, $to_file, $options['quality']);
//Monitor results with $success - returns 1 or null
echo '<br />success:['.$success.']';
}
}
}
//Set options
$from_dir = ':/source/dir';
$to_dir = ':/destination/dir';
$options = array();
$options['max_width'] = 100;
$options['max_height'] = 100;
$options['quality'] = 100;
// Make thumbs...
make_thumbnails($from_dir,$to_dir,$options);

Related

PHP Multiple Image Scripts On One Image Source

I have 2 different scripts for handling images:
The first one is a watermark script for watermarking images on the fly:
$imgpath=$_REQUEST['filename'];
header('content-type: image/jpeg');
$watermarkfile="assets/img/logo_variations/logo_watermark_75.png";
$watermark = imagecreatefrompng($watermarkfile);
list($watermark_width,$watermark_height) = getimagesize($watermarkfile);
$image = imagecreatefromjpeg($imgpath);
$size = getimagesize($imgpath);
$dest_x = ($size[0] - $watermark_width)/2;
$dest_y = ($size[1] - $watermark_height)/2;
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
So the image URL for a watermarked image is: http://example.com/watermark.php?filename=assets/img/temp/temp_share.jpg or since I'm using mod_rewrite to "pretty up" my URL: http://example.com/watermark/assets/img/temp/temp_share.jpg.
Works like a charm and my reason for doing so like this is because this is on a modeling website where I want to display the images without watermarks but I use a jquery script to change the image source of the image gets right clicked(assuming a user is trying to save the image).
The script only changes the source of any image with a class of img-protected.
I've written it to ignore any image with watermark in the URL so that it doesn't try to change the already watermarked image which would result in a url like: http://example.com/watermark/watermark/img.jpg which would result in a broken image. The other part is written to remove http://example.com from the original source so I don't end up with http://example.com/watermark/http://example.com/img.jpg.
$('.img-protected').on('mousedown', function (event) {
if (event.which == 3) {
if(this.src.indexOf("watermark") > -1) {
return false;
}
else {
src = this.src.replace('http://example.com/','');
this.src = 'http://example.com/watermark/' + src;
}
}
});
All of this works exceptionally well until I added another image handling script:
I'm using TimThumb.php which is an on the fly image resize script I use for creating gallery icons instead of uploading an icon and a full size image(this is how I wish to keep doing so as well).
The problem I am facing is this:
If I have an image that is being turned into a thumbnail using TimThumb.php which I renamed to thumb.php on my server the URL is http://example.com/thumb.php?src=gallery/goth/industrial_brick/5361ae7de9404.jpg&w=350&h=500a=c&s=1&f=11 which gives me an icon for 5361ae7de9404.jpg.
All of my icons have a class of img-protected which means on right click the above URL is going to be changed to the watermarked one.
This is where it fails.
The outputed URL when right clicked is http://example.com/watermark/http://www.example.com/thumb.php?src=gallery/goth/industrial_brick/5361ae7de9404.jpg&w=350&h=500a=c&s=1&f=11 which results in a broken image.
I manually tried making the URL into http://example.com/watermark/thumb.php?src=gallery/goth/industrial_brick/5361ae7de9404.jpg&w=350&h=500a=c&s=1&f=11 to see if that would change anything but it still results in a broken image.
What I need is to be able to also watermark the generated icons from thumb.php using watermark.php.
Is there a way to combine these two scripts or a workaround to make this work?
I'm at a complete loss here.
EDIT: I am fully aware that advanced users can still acquire the non watermarked image since it's already been downloaded to there device, but I don't expect a high volume of users to visit this particular website as this is simply a local models portfolio.

Merge multiple pictures into one

Let's suppose I want to create a face generator, where I would design several pictures for face form, ears, noses, mouth, hair. Given a combination of those pictures how can I create a new picture in PHP? For instance, a simplified version:
There is face1.png, face2.png, nose1.png and nose2.png. How could I programmatically merge face1.png with nose2.png, so the result picture would hold content from both picture?
You've basically got three options: GD, Cairo or ImageMagic. I'd recommend using the Imagick class if it's available. If not, ImageMagick through PHP system calls. If that's not available, GD will probably suffice.
It depends on your server configuration, which of these are available and which would require additional packages to be installed.
There's a very simple example in the Imagick documentation of combining images: https://secure.php.net/manual/en/imagick.compositeimage.php
I also found this example for GD:
Merge two PNG images with PHP GD library
There is a function named imagecopy. This function overrides a part of the destination image using a source image. The given part is specified as parameters. Before you tell me that this does not solve your problem, I have to add that the pixels in the destination picture will not be overriden by the pixels of the source picture if the pixels are transparent. You need to use imagealphablending and imagesavealpha on the source picture, like this:
public static function experimental($images, $width, $height, $dest = null) {
$index = 0;
if ($dest === null) {
$dest = $images[$index++];
}
while ($index < count($images)) {
imagealphablending($images[$index], true);
imagesavealpha($images[$index], true );
imagecopy($dest, $images[$index++], 0, 0, 0, 0, $width, $height);
}
return $dest;
}
If we have these two pictures:
The result will be this:
You really want make it with PHP?
Ok.
1) You can use GD library for image processing.
2) You can use imagemagic PHP wrapper -- imagic.
But I think you should use canvas on client side. And for saving result you can send base64 png image representation of canvas (or separated layers/pictures) to backend.

Image uploading concept in PHP

how to take image from one folder and rename and re-size the images and move to another folder?
I need to get image from one folder and rename and re-size the same image and move into another folder using php
You will most likely be using gd for resizing the images.
Here is a pretty crappy, but hopefully useful code sample. In this case, $originalName is the name given in the $_FILES array's tmp_name position. I am resizing to a width of 1200 in this case, with the height adapting according to such width. You might (and most likely will) not desire this behavior. This is just some ugly code I used in some courses I taught about 3 years ago, I don't have the newer samples in this computer so you will have to get used to the idea :)
$newDir is where the file will be located. by calling imagejpeg or imagepng and passing the filename as second argument, it means to the function that you wish to save the image in that location.
if ($type == 'image/jpeg') {
$original = imagecreatefromjpeg($originalName);
}
else {
$original = imagecreatefrompng($originalName);
}
$width = imagesx($original);
$height = imagesy($original);
//prepare for creation of image with width of 1000
$new_height = floor($height * (1200 / $width));
// create the 1200 width image
$tmp_img = imagecreatetruecolor(1200, $new_height);
// copy and resize old image into new image
imagecopyresized($tmp_img, $original, 0, 0, 0, 0,
1200, $new_height, $width, $height);
//create a random and unique name to identify (here it isn't that random ;)
$newDir = '/this/is/some/directory/and/filename.';
if ($type == 'image/jpeg') {
imagejpeg($tmp_img, $newDir."jpg");
}
else {
imagepng($tmp_img, $newDir."png");
}
Many file system functions are already built-in with PHP (e.g. rename), and you'll find most of what you need to resize images by using the GD library here.
There are libraries available in PHP for image resize.
Here are some useful links you may like.
http://www.fliquidstudios.com/2009/05/07/resizing-images-in-php-with-gd-and-imagick/
http://php.net/manual/en/book.image.php
PHP/GD - Cropping and Resizing Images
http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/
Use imagick http://php.net/manual/en/imagick.resizeimage.php
If I were you I would write a PE using a diffent language (one that you might be best used to) to adjust anything of the given image then just feel free to phpexec it to do all the steps you mentioned, you can sit relax and wait for the end result. HHAHAHHA :-)
Use imagick library to resize; it's good.

Image upload, resolution check, crop and preview. PHP

I am looking for a solution to upload an image, check the resolution crop it if necessary then then preview the image before it then gets printed onto a canvas.
I have found loads of examples of this but obviously nothing straight forward, plus i don't want to rip off someone elses work.
ASP is NOT an option as the site uses PHP and is on a 'nix box.
Any pointers would be much appreciated.
Basically the file will need to be POSTed to your PHP script. You can do this with HTML forms(input type='file') or jQuery background uploaders. Uploads are stored by default in the temporary directory of your web server, the current directory can be found by looking at the output of phpinfo().
Next check out the $_FILES global specifically move_uploaded_file(), you can find the image type from the type key in the $_FILES array, though that can be manipulated client side it it might be better to check the file type manually using magic byte functions.
Once you have the file uploaded then you need to manipulate it. You can use either GD or ImageMagick, ImageMagick may not be built-in to your PHP version, GD is pretty common. I am more familar with GD, so I'll suggest you check out the functions imagecreatefromjpeg()/png/gif & imagecopyresampled(), which can both crop and resample. To find out if you need to crop / resize you can check the aspect ratio. Here's a function I whipped up:
function fixRatio($x, $y, $ratio) {
$ratio = round($ratio,6);
$iRatio = round($x / $y, 6);
if ($iRatio > $ratio) {
$x = ceil($y * $ratio);
} else if ($iRatio < $ratio) {
$y = ceil($x * (1 / $ratio));
}
return array('x' => $x, 'y' => $y);
}
You input the width, height & desired aspect ratio & this will spit out an array that contains the corrected dimensions. It's probably best to specify the ratio by dividing desired height by desired width, e.g. fixRatio($x, $y, 640/480). You can then use that info to crop the image w/ imagecopyresampled(), at the same time you can specify to the function the destination width & height. So if everything must be 640x480, then you would specify that when calling imagecopyresampled(). You can then use iamgejpeg()/gif/png to output the image as a file to a public directory on your server. Since it's public you can reference it via a URL be it an HTML form asking the user to confirm if they like what they see or into a canvas element.

dynamic image resize using php

I have an image which i am going to be using as a background image and will be pulling some other images from the database that i want to show within this image. So if i am pulling only 1 image, i want the bottom part of the background image to close after the first image, if there are multiple images then i want it close after those images are shown. The problem with not using separate images is that the borders of the images have a design format and i cannot show them separately.
Take a look at this image . The design format of the right and left borders are more complicated than that to just crop them and use them. Any suggestions if there is any dynamic image resizing thing?
Yes there is. Look at the imageXXXX functions; the ones you are particularly interested in are imagecreate, imagecreatetruecolor, imagecreatefrompng, imagecopyresampled, imagecopyresized, and imagepng (assuming you're dealing with PNG images - there's similar load / save functions for jpeg, gif, and a few other formats).
You should try using the GD extension for PHP, especially have a look at imagecopyresized(). This allows you to do some basic image conversion and manipulation very easily.
A basic example that takes two GET parameters, resizes our myImage.jpg image and outputs it as a PNG image:
<?php
// width and height
$w = $_GET['w'];
$h = $_GET['h'];
// load image
$image = imagecreatefromjpeg('myImage.jpg');
// create a new image resource for storing the resized image
$resized = imagecreatetruecolor($w, $h);
// copy the image
imagecopyresized($resized, $image, 0, 0, 0, 0, $w, $h, imagesx($image), imagesy($image));
// output the image as PNG
header('Content-type: image/png');
imagepng($resized);
Have you tried PHPThumb? I used this class often and its pretty clean and lightweight. I used it here.

Categories