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
Related
I am in the lengthy process of modernizing a lot of code on my website to make it php 8.x compliant. I have never really gotten the hang of user defined functions, so the following code was not created by me.
I am trying to change create_function, which has been removed as of php 8.0, to an anonymous function.
I removed the security lines as they were irrelevant.
Any hints as to how I should proceed?
Code:
print_r($_FILES)
##produces
$_FILES is Array ( [pix] => Array ( [name] => christmas every day.jpg [type] => image/jpeg [tmp_name] => /tmp/phpWPefKh [error] => 0 [size] => 91284 ) )
Here is the outdated code:
Code:
<?php
$end=substr($_FILES['pix']['name'],-3,3);
$end=strtolower($end);
if($end=="jpg"||$end=="peg"||$end=="gif"||$end=="png") {}
else {echo"<script type=\"text/javascript\">
window.location = \"http://www.animeviews.com\"
</script>";
exit;
}
function or_f($a, $b) {
return $a || $b;
}
function file_has_extension($fn, $ext) {
if(is_array($ext))
return array_reduce(array_map(create_function('$a', 'return file_has_extension(\'' . $fn . '\', $a);'), $ext), 'or_f', false);
else
return stripos($fn, '.' . strtolower($ext)) === strlen($fn) - strlen($ext) + 1;
}
$image_extensions = array(
'png',
'jpg',
'jpeg',
'gif'
);
if(!isset($_POST['Upload']) and !isset($_POST['Overwrite']))
{
include("picform.php");
} # endif
else
{
if($_FILES['pix']['tmp_name'] == "none")
{
echo "<b>File did not successfully upload. Check the
file size. File must be less than 500K.<br>";
include("picform.php");
exit();
}
if(file_has_extension($_FILES['pix']['name'], $image_extensions))
{
echo "<b>File is not a picture. Please try another
file.</b><br>";
include("picform.php");
exit();
}
else
{
$destination = $_FILES['pix']['name'];
$destination = strtolower($destination);
$temp_file = $_FILES['pix']['tmp_name'];
if (file_exists($destination) and $_POST['Overwrite']!="Overwrite") {
echo "The file $destination already exists.";exit();
}
#########
move_uploaded_file($temp_file,$destination);
echo "<p><b>The file has successfully uploaded:</b>
{$destination}
({$_FILES['pix']['size']})</p>";
$img="http://www.animeviews.com/images/$destination";
$img = $destination;
$width = "180px";
$height = "";
// Get new dimensions
list($width1, $height1) = getimagesize($img);
if ($width =="") {$j=$height/$height1; $width = $width1 * $j;}
if ($height=="") {$j=$width/$width1; $height = $height1 * $j;}
$new_width = $width;
$new_height = $height;
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width1, $height1);
// Output
$img=preg_replace('/h.*\//','',$img);
$img=strtolower($img);
$dest="thumbs/$img";
imagejpeg($image_p,$dest);
}
}
?>
The purpose was to make sure that only images are uploaded, so create_function() or function() are not really needed. In fact, all I really needed was the following code snippet:
Code:
$end=substr($_FILES['pix']['type'], 0, 6);
$end=strtolower($end);
In short, the following code will check to see if the image being uploaded is an image. Not displayed is the code to be sure the user of the script is me. The script will overwrite the image if the same filename already exists and Overwrite was selected. A thumbnail is created and, lastly, a message is displayed saying that the file was successfully uploaded with the size.
Here is the full code:
Code:
<?php
$end=substr($_FILES['pix']['type'], 0, 6);
$end=strtolower($end);
if($end=="image/") {}
else {echo"<script type=\"text/javascript\">
window.location = \"http://www.animeviews.com/images/picform.php\"
</script>";
exit;
}
if(!isset($_POST['Upload']) and !isset($_POST['Overwrite']))
{
include("picform.php");
} # endif
else
{
if($_FILES['pix']['tmp_name'] == "none")
{
echo "<b>File did not successfully upload. Check the
file size. File must be less than 500K.<br>";
include("picform.php");
exit();
}
$destination = $_FILES['pix']['name'];
$destination = strtolower($destination);
$temp_file = $_FILES['pix']['tmp_name'];
if (file_exists($destination) and $_POST['Overwrite']!="Overwrite") {
echo "The file $destination already exists.";exit();
}
#########
move_uploaded_file($temp_file,$destination);
echo "<p><b>The file has successfully uploaded:</b>
{$destination}
({$_FILES['pix']['size']})</p>";
$img="http://www.animeviews.com/images/$destination";
$img = $destination;
$width = "180";
##$height = "";
// Get new dimensions
list($width1, $height1) = getimagesize($img);
if (!isset($width)) {$j=$height/$height1; $width = $width1 * $j;}
if (!isset($height)) {$j=$width/$width1; $height = $height1 * $j;}
$new_width = $width;
$new_height = $height;
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width1, $height1);
// Output
$img=preg_replace('/h.*\//','',$img);
$img=strtolower($img);
$dest="thumbs/$img";
imagejpeg($image_p,$dest);
}
i'll try to describe the solution:
Legacy code: create_function('$a', 'return file_has_extension(\'' . $fn . '\', $a);')
Perfect code: function ($a) use ($fn) { return file_has_extension ($fn, $a); }
Explanation: in the first case, you can see the removed function named create_function, which creates a new closure (example of simple closue: function ($args) use ($extraArg - here is extra vars. which you need into the closure, 'use' - construction can be ummitted) { return ...$args }. Closure is equals type callable, you can read this documentation and see, that the first argument of previous function (it's array_map) will be the callable type, all you need pass the same type with the same behavior).
In the second case, you can see some strange construction like this use ($fn), it's necessary, because the closure|callable type has the own variable scope (more here).
More, about Closure and him scope here.
Rewritten file_has_extension function:
function file_has_extension($fn, $ext) {
if (is_array($ext)){
return array_reduce(
array_map(
function ($a) use ($fn) {
return file_has_extension($fn, $a);
},
$ext
),
function ($a, $b) {
return $a || $b;
},
false
);
}
return stripos($fn, '.' . strtolower($ext)) === strlen($fn) - strlen($ext) + 1;
}
I'm using a script for resize photos to another folder and keep the same name automaticaly found here and working great!
I have hundreds of photos in my source folder and i'm going to do this action often. I would like to optimize the time by making it resize the photos only if it sees the photos doesn't exist in the destination folder. How can we do that?
Here is the full code used:
function imageResize($file, $path, $height, $width)
{
$target = 'smallphotos/';
$handle = opendir($path);
if($file != "." && $file != ".." && !is_dir($path.$file))
{
$thumb = $path.$file;
$imageDetails = getimagesize($thumb);
$originalWidth = $imageDetails[0];
$originalHeight = $imageDetails[1];
if($originalWidth > $originalHeight)
{
$thumbHeight = $height;
$thumbWidth = ($originalWidth/($originalHeight/$thumbHeight));
}
else
{
$thumbWidth = $width;
$thumbHeight = ($originalHeight/($originalWidth/$thumbWidth));
}
$originalImage = ImageCreateFromJPEG($thumb);
$thumbImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);
ImageCopyResized($thumbImage, $originalImage, 0, 0, 0, 0, $thumbWidth,
$thumbHeight, $originalWidth, $originalHeight);
$filename = $file;
imagejpeg($thumbImage, $target.$filename, 100);
}
closedir($handle);
}
$source = "photos";
$directory = opendir($source);
//Scan through the folder one file at a time
while(($file = readdir($directory)) != false)
{
echo "<br>".$file;
//Run each file through the image resize function
imageResize($file, $source.'/', 640, 480);
}
Seems like you could just add one more condition to the resize function
if ($file != "." && $file != ".." && !is_dir($path.$file) && !is_file($target.$file) {...
This should keep it from trying to do anything if the target file already exists.
Another option would be to check if the destination file exists before calling the function
while (($file = readdir($directory)) != false) {
echo "<br>".$file;
//Run each file through the image resize function (if it has not already been resized)
if (!is_file("smallphotos/$file")) {
imageResize($file, $source.'/', 640, 480);
}
}
These are my first steps with AWS S3, so and my goal is to use imagick for manipulating the image before I upload to S3 AWS.
I use this function for resize and scale the image (works perfect on output browser):
function resizeImg($img, $width, $height) {
$i = new Imagick($img);
$gig = $i->getImageGeometry();
// crop the image
if(($gig['width']/$width) < ($gig['height']/$height)) {
$i->cropImage($gig['width'], floor($height * $gig['width'] / $width), 0, (($gig['height'] - ($height * $gig['width'] / $width)) / 2));
} else {
$i->cropImage(ceil($width * $gig['height'] / $height), $gig['height'], (($gig['width'] - ($width * $gig['height'] / $height)) / 2), 0);
}
$i->ThumbnailImage($width, $height, true);
$i->setImageFormat("jpeg");
$i->setImageCompressionQuality(90);
$i->getimageblob(); // I tried it with and without getimageblob
return $i;
}
Thats my attempt, Upload to S3:
$tmpImg = $_FILES['inputImage']['tmp_name'];
$newImgFile = resizeImg($tmpImg, 100, 100);
$s3->putObjectFile($newImgFile, BUCKET_NAME, $newfilename, S3::ACL_PUBLIC_READ);
But I get this error:
Warning: S3::inputFile(): Unable to open input file: ���� in.....
What I`m doing wrong?
Is imagick not compatible with S3 AWS?
Or is there a better way?
And my next goal is to put different image resizes to S3, e.g 100x100, 300x300.... from same input file, but of course I have to solve before the first goal.
EXTRA:
With this solution from here:
PHP Imagick: Write Image directly to Amazon S3?
I get this Error:
Warning: S3::putObject(): [SignatureDoesNotMatch] The request signature we calculated does not match the signature you provided. Check your key and signing method.
If I do this: $new = urlencode($new); or $new = strtolower($new); ...Works to upload but no readable!
The error came from extra spaces or slashes in there, so far as I have understood
And if its important, here the Url from the image in S3
https->awsCount.xxxx.xxxxx/img.jpg?AWSAccessKeyId=xxxx&Expires=1383787878&Signature=xxxx&x-amz-security-token=AQoDYXdzEGAasAJlJXrt/7FPf84wE9stfgBfEoWaPMDHlubQBlQ6oMY6sNMT4cizkEm9khypHulLB/zJ%2BbqqAErvFBKKs2I9bKDBzrKYKhgRn%2Bta057CZaLougsxHLRGquhd5H26br/Odkq98%2BoDTnfK0LHFa9vYbX6sXDIzCSHcZx4%2B5o0y3cKlxCMsYLqw6wYD1DNjJ%2BHlWWuh%2B6V0FtpbYaErB1XUZfRRZdx3ZPEOvyZxQS7uzP8C3B1nK0wo3uqqSAhn9PPtQt5jrRutYRao2KugxK8TbkZbr/v5NOYSbpc%2BmI2iYYrUjylqgenzf85Avss0CA1GfOzg%2BMs2/TQ7evH7epr09B8Vyd89Gk1XQpVMyrTSvbzDYE8UCcgrUrXgdHTYWdGLVZ%2BBHzft9nHtNhggePD6AXMuIP%2Ba6ZMF
You are trying to put an object from S3 from a file (putObjectFile takes a file name as an argument) but you're giving the image blob as a parameter, instead of a file name.
You should do something like this:
In resizeImg:
return $i-> getimageblob(); //(this is just an assumption)
For uploading to S3, something similar to this:
$s3 = new AmazonS3();
$s3->batch()->create_object(__BUCKET__,$filename, array(
'body' => $object,
'acl' => AmazonS3::ACL_PUBLIC,
'contentType' => $contentType,
'storage' => AmazonS3::STORAGE_REDUCED
));
$file_upload_response = $s3->batch()->send();
Note that this is using the PHP SDK V1 (not sure if you're using V2).
I'll have the answer, I show the whole code for each one:
if (!empty($_FILES["input_file"])) {
if ($_FILES["input_file"]["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// Move/Copy from temporary file to local file
$success = move_uploaded_file($_FILES["input_file"]["tmp_name"],
'local_temp_file_directory/' . $_FILES["input_file"]["name"]);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
}
// I make a function to get the local file and save the edited file
function resizeImg($img_from_local_file, $width, $height, $pathToSaveImg) {
$i = new Imagick($img_from_local_file);
$gig = $i->getImageGeometry();
if(($gig['width']/$width) < ($gig['height']/$height)) {
$i->cropImage($gig['width'], floor($height * $gig['width'] / $width), 0, (($gig['height'] - ($height * $gig['width'] / $width)) / 2));
} else {
$i->cropImage(ceil($width * $gig['height'] / $height), $gig['height'], (($gig['width'] - ($width * $gig['height'] / $height)) / 2), 0);
}
$i->ThumbnailImage($width, $height,true);
$i->setImageFormat("jpeg");
$i->setImageCompressionQuality(90);
$i->writeImage($pathToSaveImg);
return $i->getimage();
}
// Call the resizeImg function
resizeImg("local_temp_file_directory/".$_FILES["input_file"]["name"], 40, 40, "local_temp_file_directory/resized_".$_FILES["input_file"]["name"]);
$s3->putObject(
S3::inputFile("local_temp_file_directory/resized_".$_FILES["input_file"]["name"]),
BUCKET_NAME,
"make_a_new_image_name".date("his").".jpg",
S3::ACL_PUBLIC_READ,
array(),
array("Content-Type"=>'image/jpeg'));
// Remove the temporary local file
unlink("local_temp_file_directory/".$_FILES["input_file"]["name"]);
unlink("local_temp_file_directory/resized_".$_FILES["input_file"]["name"]);
Thats it... Enjoy it!
you can doing these :
$outFile = $this->get('kernel')->getRootDir().'/../web/uploads/imageWithImagick.png';
$url = "http//......";
$img = new Imagick();
$dir = "images/profile";
$uploader = $this->get('core_storage.uploader');
$width = 300;
$height = 500;
$compression = 90;
$imageFormat = "jpeg";
$uploader->uploadImagick($url,$img,$outFile,$width,$height,$dir,$imageFormat,$compression);
and the function :
public function uploadImagick($url,$img,$outFile,$width,$height,$dir,$imageFormat,$compression)
{
$handle = fopen($url, 'rb');
$img->readImageFile($handle);
$gig = $img->getImageGeometry();
if(($gig['width']/$width) < ($gig['height']/$height)) {
$img->cropImage($gig['width'], floor($height * $gig['width'] / $width), 0, (($gig['height'] - ($height * $gig['width'] / $width)) / 2));
} else {
$img->cropImage(ceil($width * $gig['height'] / $height), $gig['height'], (($gig['width'] - ($width * $gig['height'] / $height)) / 2), 0);
}
$img->thumbnailImage($width,$height);
$img->setImageFormat($imageFormat);
$img->setImageCompressionQuality($compression);
$img->writeImage($outFile);
// Generate a unique filename based on the date and add file extension of the uploaded file
$filename = sprintf('%s/%s.%s', $dir, uniqid(), $imageFormat);
$adapter = $this->filesystem->getAdapter();
$adapter->write($filename, file_get_contents($outFile));
unlink($outFile);
return $filename;
}
I have a snippet of code used to upload images into my gallery. All seems to work until it gets to the last part of the code.
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$pubID = $_POST['pubID'];
$size = 260; // the thumbnail height
$filedir = '../images/gallery/'.$pubID.'/'; // the directory for the original image
$thumbdir = '../images/gallery/'.$pubID.'/thumb/'; // the directory for the thumbnail image
$maxfile = '2000000';
$mode = '0777';
$userfile_name = $_FILES['Gallimage']['name'];
$userfile_tmp = $_FILES['Gallimage']['tmp_name'];
$userfile_size = $_FILES['Gallimage']['size'];
$userfile_type = $_FILES['Gallimage']['type'];
if (isset($_FILES['Gallimage']['name']))
{
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$userfile_name;
move_uploaded_file($userfile_tmp, $prod_img);
chmod ($prod_img, octdec($mode));
$sizes = getimagesize($prod_img);
$aspect_ratio = $sizes[1]/$sizes[0];
if ($sizes[1] <= $size)
{
$new_width = $sizes[0];
$new_height = $sizes[1];
}else{
$new_height = $size;
$new_width = abs($new_height/$aspect_ratio);
}
$destimg=ImageCreateTrueColor($new_width,$new_height)
or die('Problem In Creating image');
$srcimg=ImageCreateFromJPEG($prod_img)
or die('Problem In opening Source Image');
if(function_exists('imagecopyresampled'))
{
imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
or die('Problem In resizing');
}else{
Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
or die('Problem In resizing');
}
ImageJPEG($destimg,$prod_img_thumb,90)
or die('Problem In saving');
imagedestroy($destimg);
}
The error arrives on this line: ImageJPEG($destimg,$prod_img_thumb,90).
Here is the error code line 84 being the : ImageJPEG($destimg,$prod_img_thumb,90)
Warning: imagejpeg() [function.imagejpeg]: Unable to open '../images/gallery/264/thumb/Hair-Salon-1.jpg' for writing: No such file or directory in /home/www/public_html/console/gallery.php on line 84. Problem In saving
It's conceivable that the directory '../images/gallery/'.$pubID.'/thumb/' does not exist. Try to use mkdir('../images/gallery/'.$pubID.'/thumb/', 0775, true) and see what happens. This should create writable directories along the path, down to thumb at the end.
Try this code with a bit more error checking, a few corrections and some general improvements. Everything commented, if you don't understand anything just ask:
// Try not to over-use parenthesis, it makes code less readable. You only need them to group conditions.
if (isset($_POST["MM_insert"]) && $_POST["MM_insert"] == "form1") {
// Pass through basename() for sanitization
$pubID = basename($_POST['pubID']);
$size = 260; // the thumbnail height
$filedir = '../images/gallery/'.$pubID.'/'; // the directory for the original image
$thumbdir = '../images/gallery/'.$pubID.'/thumb/'; // the directory for the thumbnail image
$maxfile = '2000000';
// PHP understands proper octal representations - no need to turn it into a string
$mode = 0777;
if (isset($_FILES['Gallimage']['name'])) {
// Get upload info and create full paths
$userfile_name = $_FILES['Gallimage']['name'];
$userfile_tmp = $_FILES['Gallimage']['tmp_name'];
$userfile_size = $_FILES['Gallimage']['size'];
$userfile_type = $_FILES['Gallimage']['type'];
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$userfile_name;
// Create directories if they don't exist - this is the crux of your problem
if (!is_dir($filedir)) {
mkdir($filedir, $mode, TRUE)
or die('Unable to create storage directory');
}
if (!is_dir($thumbdir)) {
mkdir($thumbdir, $mode, TRUE))
or die('Unable to create thumb directory');
}
// Move it to the correct location and set permissions
move_uploaded_file($userfile_tmp, $prod_img)
or die('Unable to move file to main storage directory');
chmod($prod_img, $mode)
or die('Unable to set permissions of file');
// Get info about the image
$sizes = getimagesize($prod_img);
$aspect_ratio = $sizes[1] / $sizes[0];
if ($sizes[1] <= $size) {
$new_width = $sizes[0];
$new_height = $sizes[1];
} else {
$new_height = $size;
$new_width = abs($new_height / $aspect_ratio);
}
// Create image resources
$destimg = imagecreatetruecolor($new_width, $new_height)
or die('Problem in creating image');
$srcimg = imagecreatefromjpeg($prod_img)
or die('Problem in opening source Image');
// Manipulate the image
if (function_exists('imagecopyresampled')) {
imagecopyresampled($destimg, $srcimg, 0, 0, 0, 0, $new_width, $new_height, imagesx($srcimg), imagesy($srcimg))
or die('Problem in resizing');
} else {
imagecopyresized($destimg, $srcimg, 0, 0, 0, 0, $new_width, $new_height, imagesx($srcimg), imagesy($srcimg))
or die('Problem in resizing');
}
// Save the thumbnail and destroy the resources
imagejpeg($destimg, $prod_img_thumb, 90)
or die('Problem in saving');
imagedestroy($destimg);
}
// More code here? If not, merge all of this into a single if block
}
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