how to make thumbnails with php - php

I was just wondering how I can make thumbnails of images stored in hdd and use them in an html page, also I need the thumbnails to be able to enlarge (to their original size) if clicked on preferably inside a div tag on the same page, I would appreciate if anyone could put me in the right direction
thanks

You will need the GD extension enabled. The following code will create a thumbnail file in a subdirectory called ~tmb for a JPEG, PNG and GIF file:
$invalid = true;
if ($file != '.' and $file != '..') {
if (filetype($path_abs.$file) == "file") {
$ext = strtolower(substr($file,strrpos($file,'.')+1));
if ($ext == 'jpg' || $ext == 'jpeg') {
$origimg = #imagecreatefromjpeg($path_abs.$file);
} elseif ($ext == 'png') {
$origimg = #imagecreatefrompng($path_abs.$file);
} elseif ($ext == 'gif') {
$origimg = #imagecreatefromgif($path_abs.$file);
}
if ($origimg !== false) {
$nheight = 0;
$nwidth = 0;
$use_orig = false;
if ($width<=160 and $height<160) {
$nwidth = $width;
$nheight = $height;
$use_orig = true;
$invalid = false;
} else {
if ($width>$height and $width>0) {
$nheight = intval((160 / $width) * $height);
$nwidth = 160;
} elseif ($height>0) {
$nwidth = intval((160 / $height) * $width);
$nheight = 160;
} else {
$image = false;
}
if ($nheight > 0 and $nwidth > 0) {
$newimg = imagecreatetruecolor($nwidth, $nheight);
$bgc = imagecolorallocate ($newimg, 238, 238, 238);
imagefilledrectangle ($newimg, 0, 0, $nwidth, $nheight, $bgc);
if (#imagecopyresampled($newimg, $origimg, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
$image = imagejpeg($newimg, $path_abs.'~tmb/'.$file);
$invalid = false;
} elseif (#imagecopyresized($newimg, $origimg, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
$image = imagejpeg($newimg, $path_abs.'~tmb/'.$file);
$invalid = false;
}
}
}
}
}
}
if (!$invalid) {
if ($use_orig) {
echo '<img src="'.$file.'" alt="" />';
} else {
echo '<img src="~tmb/'.$file.'" alt="" />';
}
} else {
echo '<p>Error for file '.$file.'</p>';
}
In the above code, it resizes them to 160x160, though maintaining aspect ratio.

The gd library allows you to manipulate images.
You will find an article to generate thumbnails here.
If you want to allow your users to view the thumbnail and the original size, the best way is to keep the two versions.
And to display either one or the other.

its so simple,if you have any queries mail at karthid#in.com
$ffmpeg = "ffmpeg Installed path"
$flvfile = "source video file with root path"
$png_path " "Destination video file with root path and file type"
exec("$ffmpeg -y -i $flvfile -vframes 1 -ss 00:01:60 -an -vcodec png -f rawvideo -s 110x90 $png_path");
all the best....

You can use the GD library in PHP to load and resize your images to generate the thumbnails
http://us.php.net/manual/en/image.examples.php

Lookup the PECL extension Imagick. It's usually installable with standard package-managers.
http://se2.php.net/Imagick
You can either dynamically create the thumbnails and serve them using .php files (slow) or make a thumbnail-copy that you store on the server (prefered)

the best way I found is to use the phpThumb class (http://phpthumb.sourceforge.net/).
It has everything you need and more, including caching, filters, watermarks and other cool stuff. Just look at the demo page.

maxImageUpload is useful for creating thumbnails, normal image with an original image.
You can use jQuery to enlarge the thumbnail image.

In my experience GD is not very memory-effective for large images, so I strongly encourage you to use Imagick. I`ve written a code snippet for thumbnail generation with php using the Imagick library. You can modify it to save the image instead of echoing it using http://php.net/manual/en/imagick.writeimage.php

Related

Compress & resize images using PHP GD lib not working for png and weird results for jpg

I am trying to compress & resize my images using the php GD library. Nearly every answer on SO and everywhere else is the same, but for my solution, the PNG's are not being correctly transformed, and some jpg's are giving bizarre results.
This is the code I am using:
public function resizeImages() {
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = FCPATH . 'design/img/test/'; //Source Image Directory End with Slash
$DestImagesDirectory = FCPATH . 'design/img/test/thumb/'; //Destination Image Directory End with Slash
$NewImageWidth = 150; //New Width of Image
$NewImageHeight = 150; // New Height of Image
$Quality = 90; //Image Quality
//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
while(($file = readdir($dir))!== false){
$imagePath = $ImagesDirectory.$file;
$destPath = $DestImagesDirectory.$file;
$checkValidImage = #getimagesize($imagePath);
if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if (resize_image($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
{
echo $file.' resize Success!<br />';
/*
Now Image is resized, may be save information in database?
*/
} else {
echo $file.' resize Failed!<br />';
}
}
}
closedir($dir);
}
}
and the resize_image function looks like this:
function resize_image($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
$NewWidth = ceil($ImageScale*$iWidth);
$NewHeight = ceil($ImageScale*$iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
$imagetype = strtolower(image_type_to_mime_type($type));
switch($imagetype)
{
case 'image/jpeg':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
case 'image/png':
$NewImage = imagecreatefrompng($SrcImage);
break;
default:
return false;
}
//allow transparency for pngs
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves, true);
// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
switch ($imagetype) {
case 'image/jpeg':
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
case 'image/png':
if(imagepng($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
default:
return false;
}
return true;
}
}
Every single png is not working, it just returns a file with 0 bytes and "file type is not supported", even though the type is recognized as .PNG in Windows...
Some JPG's return a weird result as well, see the following screenshot which indicates my issues regarding png's and some jpg's:
1) Do not use getimagesize to verify that the file is a valid image, to mention the manual:
Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.
$checkValidImage = exif_imagetype($imagePath);
if(file_exists($imagePath) && ($checkValidImage == IMAGETYPE_JPEG || $checkValidImage == IMAGETYPE_PNG))
2) While imagejpeg() accepts quality from 0 to 100, imagepng() wants values between 0 and 9, you could do something like that:
if(imagepng($NewCanves,$DestImage,round(($Quality/100)*9)))
3) Using readdir () you should skip the current directory . and the parent..
while(($file = readdir($dir))!== false){
if ($file == "." || $file == "..")
continue;
edit
Point 2 is particularly important, imagepng () accepts values greater than 9 but then often fails with error in zlib or libpng generating corrupt png files.
I tried resizing some png and jpeg and I didn't encounter any problems with these changes.

How can I create custom thumbnails using php gd

i wanted to create a thumbnail with specific custom width & height. The function am using only create a thumbnail with a maximum set width/height.
How do i tweak the below function to give me a defined width/height e.g 50x50, 75x75, 100x100.
$original_photo = "photos/photo.extension";
$newcopy = "photos/thumbnails/photo.extension";
$copy_w = 50;
$copy_h = 50;
$extension = explode('.', 'photo.extension');
$extension = end($extension);
function create_thumbnail($original_photo, $newcopy, $copy_w, $copy_h, $extension) {
list($original_w, $original_h) = getimagesize($original_photo);
$scale_ratio = $original_w / $original_h;
if (($copy_w / $copy_h) > $scale_ratio) {
$copy_w = $copy_h * $scale_ratio;
} else {
$copy_h = $copy_w / $scale_ratio;
}
$img = '';
if ($extension == 'gif') {
$img = imagecreatefromgif($original_photo);
} elseif ($extension == 'png') {
$img = imagecreatefrompng($original_photo);
} else {
$img = imagecreatefromjpeg($original_photo);
}
$true_color = imagecreatetruecolor($copy_w, $copy_h);
imagecopyresampled($true_color, $img, 0, 0, 0, 0, $copy_w, $copy_h, $original_w, $original_h);
if (imagejpeg($true_color, $newcopy, 80) == true) {
return true;
} else {
return false;
}
}
Working with images in PHP/GD can be a pain. There are a lot of edge cases, particularly when transparent PNG/GIFs are manipulated.
If possible, I shamelessly recommend a library I wrote to handle things like this: SimpleImage 3.0
Using SimpleImage, you can achieve the desired effect with the following code:
// Load the image from image.jpg
$image = new \claviska\SimpleImage('image.jpg');
// Create a 50x50 thumbnail, convert to PNG, and write to thumbnail.png
$image->thumbnail(50, 50)->toFile('thumbnail.png', 'image/png');
See this page for more details on how the thumbnail method works and available arguments.

Compress and RESCALE uploaded image

I have a function that uploads files up to 8MB but now I also want to compress or at least rescale larger images, so my output image won't be any bigger than 100-200 KB and 1000x1000px resolution. How can I implement compress and rescale (proportional) in my function?
function uploadFile($file, $file_restrictions = '', $user_id, $sub_folder = '') {
global $path_app;
$new_file_name = generateRandomString(20);
if($sub_folder != '') {
if(!file_exists('media/'.$user_id.'/'.$sub_folder.'/')) {
mkdir('media/'.$user_id.'/'.$sub_folder, 0777);
}
$sub_folder = $sub_folder.'/';
}
else {
$sub_folder = '';
}
$uploadDir = 'media/'.$user_id.'/'.$sub_folder;
$uploadDirO = 'media/'.$user_id.'/'.$sub_folder;
$finalDir = $path_app.'/media/'.$user_id.'/'.$sub_folder;
$fileExt = explode(".", basename($file['name']));
$uploadExt = $fileExt[count($fileExt) - 1];
$uploadName = $new_file_name.'_cache.'.$uploadExt;
$uploadDir = $uploadDir.$uploadName;
$restriction_ok = true;
if(!empty($file_restrictions)) {
if(strpos($file_restrictions, $uploadExt) === false) {
$restriction_ok = false;
}
}
if($restriction_ok == false) {
return '';
}
else {
if(move_uploaded_file($file['tmp_name'], $uploadDir)) {
$image_info = getimagesize($uploadDir);
$image_width = $image_info[0];
$image_height = $image_info[1];
if($file['size'] > 8000000) {
unlink($uploadDir);
return '';
}
else {
$finalUploadName = $new_file_name.'.'.$uploadExt;
rename($uploadDirO.$uploadName, $uploadDirO.$finalUploadName);
return $finalDir.$finalUploadName;
}
}
else {
return '';
}
}
}
For the rescaling I use a function like this:
function dimensions($width,$height,$maxWidth,$maxHeight)
// given maximum dimensions this tries to fill that as best as possible
{
// get new sizes
if ($width > $maxWidth) {
$height = Round($maxWidth*$height/$width);
$width = $maxWidth;
}
if ($height > $maxHeight) {
$width = Round($maxHeight*$width/$height);
$height = $maxHeight;
}
// return array with new size
return array('width' => $width,'height' => $height);
}
The compression is done by a PHP function:
// set limits
$maxWidth = 1000;
$maxHeight = 1000;
// read source
$source = imagecreatefromjpeg($originalImageFile);
// get the possible dimensions of destination and extract
$dims = dimensions(imagesx($source),imagesy($source),$maxWidth,$maxHeight);
// prepare destination
$dest = imagecreatetruecolor($dims['width'],$dims['height']);
// copy in high-quality
imagecopyresampled($dest,$source,0,0,0,0,
$width,$height,imagesx($source),imagesy($source));
// save file
imagejpeg($dest,$destinationImageFile,85);
// clear both copies from memory
imagedestroy($source);
imagedestroy($dest);
You will have to supply $originalImageFile and $destinationImageFile. This stuff comes from a class I use, so I edited it quite a lot, but the basic functionality is there. I left out any error checking, so you still need to add that. Note that the 85 in imagejpeg() denotes the amount of compression.
you can use a simple one line solution through imagemagic library the command will like this
$image="path to image";
$res="option to resize"; i.e 25% small , 50% small or anything else
exec("convert ".$image." -resize ".$res." ".$image);
with this you can rotate resize and many other image customization
Take a look on imagecopyresampled(), There is also a example that how to implement it, For compression take a look on imagejpeg() the third parameter helps to set quality of the image, 100 means (best quality, biggest file) and if you skip the last option then default quality is 75 which is good and compress it.

Old PHP GD code no longer working

I have a function which resizes images and whilst it works fine on my test server, it doesn#t work on the new live server. The error message i get is
Warning: imagejpeg(): Unable to open ' /home/sites/public_html/images/2013-24-1-240x300.jpg' for writing: No such file or directory in /home/sites/public_html/includes/functions/html_output.php on line 352
line 352 in the code below is the imagejpeg line near to the bottom. If its creating the image on the fly, I dont understand why its trying to open the file.
Images folder is writeable (changed to 777 to check) as the original image is showing fine. GD is enabled on the live server bundled (2.0.34 compatible)
Both versions of PHP and GD are the same now on both servers. Only difference is test server is running WAMP and live is a linux.
function image_resample($src,$width,$height) {
define(JPEGQUALITY, 75);
define(ALLOWSQUASH,0.10);
if ($src=='') {
return $src;
}
$i = #getimagesize( $src ); // 1-gif (ignore), 2-jpeg, 3-png
if (!(($width == SMALL_IMAGE_WIDTH) && ($height == SMALL_IMAGE_HEIGHT)) &&
!(($width == MEDIUM_IMAGE_WIDTH) && ($height == MEDIUM_IMAGE_HEIGHT))&&
!(($width == LARGE_IMAGE_WIDTH) && ($height == LARGE_IMAGE_HEIGHT))) {
return $src; // can amend to work with other images
}
if (!( ($i[2] == 3) || ($i[2] ==2))) {
return $src;
}
$file = preg_replace( '/\.([a-z]{3,4})$/i', "-{$width}x{$height}.\\1", $src ); // name of resampled image
if (is_file( $file ) ) {
return $file;
}
$scr_w = $i[0];
$scr_h = $i[1];
if (($scr_w * $scr_h * $width * $height) == 0) {
return $src;
}
$howsquashed = ($width / $height * $scr_h / $scr_w);
if (((1 / (1 + ALLOWSQUASH)) < $howsquashed) && ($howsquashed < (1 + ALLOWSQUASH))) $simpleway='true';
$scalefactor = min($width/$scr_w, $height/$scr_h);
$scaled_w = (int)($scr_w * $scalefactor);
$scaled_h = (int)($scr_h * $scalefactor);
$offset_w = max(0,round(($width - $scaled_w) / 2,0));
$offset_h = max(0,round(($height - $scaled_h) / 2));
$dst = DIR_FS_CATALOG . '/' . $file;
$dstim = #imagecreatetruecolor ($width, $height);
$background_color = imagecolorallocate ($dstim, 255, 255, 255);
imagefilledrectangle($dstim, 0, 0, $width, $height, $background_color);
if ( $i[2] == 2) {
$srcim = #ImageCreateFromJPEG ($src); // open
}
elseif ( $i[2] == 3) {
$srcim = #ImageCreateFromPNG ($src);
}
if ($simpleway == 'true') {
imagecopyresampled ($dstim, $srcim, 0, 0, 0, 0, $width, $height, $scr_w, $scr_h);
}
else {
$intim = #imagecreatetruecolor ($width, $height);
imagecopyresampled ($intim, $srcim, $offset_w, $offset_h, 0, 0, $scaled_w, $scaled_h, $scr_w, $scr_h);
imagecopy ( $dstim, $intim, $offset_w, $offset_h, $offset_w, $offset_h, $scaled_w, $scaled_h);
imagedestroy ($intim);
}
if ( $i[2] == 2) {
imagejpeg ($dstim , $dst , JPEGQUALITY);
}
elseif ( $i[2] == 3) {
imagepng ($dstim , $dst);
}
imagedestroy ($srcim);
imagedestroy ($dstim);
return $file; // Use the newly resampled image
}
the message is pretty clear
Warning: imagejpeg(): Unable to open ' /home/sites/public_html/images/2013-24-1-240x300.jpg'
for writing: No such file or directory in
/home/sites/public_html/includes/functions/html_output.php on line 352
if the directory exists chmod it so the apache user can write to it.
if the directory doesnt exist create it and then chmod it (644 should be enough)
if the file exists already - it can not over write it, So chmod the file (its likely you used SCP to transfer it and its under the user you SCP'ed as) ls -l to confirm the permissions

A script to rewrite all images that are a certain width in a different size?

I am using the GD library with PHP.
Basically, I've made a design change and need to resize a whole bunch of images that are a certain width.
ie anything that is 876px wide needs to be 828px.
Is there a way to loop through all JPG files in a directory, check their width dimension, and if they equal X then grab their existing file name, rescale down to the same name?
Just need to use imagecopyresampled() in a loop.
$path = "/my/path/to/jpgs";
$targetWidth = 876;
$newWidth = 828;
$imageQuality = 95;
if (is_dir($path)) {
$dHandle = opendir($path);
if ($dHandle) {
while (($cFileName = readdir($dHandle)) !== false) {
if (!preg_match("/\.jpg$/", $cFileName)) {
continue;
}
$cImagePath = $path . $cFileName;
list ($cWidth, $cHeight) = getimagesize($cImagePath);
if ($cWidth == $targetWidth) {
$cImage = imagecreatefromjpeg($cImagePath);
if ($cImage === false) {
echo "Error reading: " . $cImagePath . "\n";
continue;
}
$cNewHeight = round($cHeight * ($newWidth / $cWidth));
$cNewImage = imagecreatetruecolor($newWidth, $cNewHeight);
imagecopyresampled($cNewImage, $cImage, 0, 0, 0, 0, $newWidth, $cNewHeight, $cWidth, $cHeight);
if (imagejpeg($cNewImage, $cImagePath, $imageQuality) === false) {
echo "Error writing: " . $cImagePath . "\n";
continue;
}
}
}
closedir($dHandle);
}
}
There are a lot of image resize scripts out there...just google... but if you're looking to build something yourself, you would basically use getimagesize and imagecopyresampled

Categories