I have written a function for creating a thumbnail from .jpg image. But what I want to do is whenever the function gets called, same image should be saved as 1.jpg,2.jpg,3.jpg at the same destination.
I have used Sessions and static variable concept but to no success.
Here is my code.
this is thumbsave.php file
<?php
session_start();
$_SESSION['sid']=$k=1;
function createThumb($fpath)//fpath will be passed here as parameter.
{
$ims = imagecreatefromjpeg($fpath);
$imd = imagecreatetruecolor(100, 100);
imagecopyresized($imd, $ims, 0, 0, 0, 0, 100, 100, imagesx($ims),
imagesy($ims));
imagejpeg($imd,"saveimages/" . $_SESSION['sid'] . ".jpg");
$_SESSION['sid'] = $_SESSION['sid'] + 1;
imagedestroy($ims);
imagedestroy($imd);
echo "Thumbnail Created and Saved at the Destination";
}
?>
Here is my code for dynamicthumb.php
<?php
include("include/thumbsave.php");
createThumb("imgs/m1.jpeg");
?>
So,when I run the dynamicthumb.php file the image stored at the imgs folder must be stored inside saveimages folder. But here only 1 image is saved, not multiple copies are generated like 2.jpg,3.jpg.
You can use a file_exists loop if you are positive the name of the thumbnail will always be numerical:
function createThumb($fpath)
{
$ims = imagecreatefromjpeg($fpath);
$imd = imagecreatetruecolor(100, 100);
imagecopyresized($imd, $ims, 0, 0, 0, 0, 100, 100, imagesx($ims), imagesy($ims));
$thumb = 1;
while ( file_exists('saveimages/'. $thumb .'.jpg') ) { $thumb++; }
imagejpeg($imd,'saveimages/'. $thumb .'.jpg');
imagedestroy($ims);
imagedestroy($imd);
echo 'Thumbnail Created and Saved at the Destination as '. $thumb .'.jpg';
}
However I question the logic behind what you are asking for... as this suggests that every thumbnail you create will just be a sequential number, all stored in the same directory?
You may have better luck using a counter db field or file, as doing file_exists on a folder with thousands and growing, can hurt performance.
So a file based counter solution could be thus:
function createThumb($fpath)
{
$ims = imagecreatefromjpeg($fpath);
$imd = imagecreatetruecolor(100, 100);
imagecopyresized($imd, $ims, 0, 0, 0, 0, 100, 100, imagesx($ims), imagesy($ims));
$thumb = file_get_contents('saveimages/thumbcount.txt');
$thumb++; file_put_contents('saveimages/thumbcount.txt',$thumb);
imagejpeg($imd,'saveimages/'. $thumb .'.jpg');
imagedestroy($ims);
imagedestroy($imd);
echo 'Thumbnail Created and Saved at the Destination as '. $thumb .'.jpg';
}
Just be sure to prime the thumbcount.txt with a 1 so it has something to begin with.
This is the line responsible for saving image to file:
imagejpeg($imd,"saveimages/" . $_SESSION['sid'] . ".jpg");
You can update it to use $fpath instead of ,$_SESSION['sid']:
imagejpeg($imd, $fpath);
But beware, your path should end with .jpg.
Related
I have problem with my reszie image (code) when I run this code in localhost the code is work fine, but when I implement in website. the code give a warning.
<br /><b>Warning</b> : imagecreatefromjpeg([-1, [], 17, 1, 18, 1, 19, 23, true, [true, true],26,1,27,1,30,1,33]) expects parameter 1 to be resource, boolean given in <b>fungsi/f_upload_banner.php</b> on line <b>34</b><br />
This is my code for resize
<?php
$target_dir = "../uploads/images/banner/";
$image1 =$_FILES['txtfile']['name'];
$filename1 = stripslashes($_FILES['txtfile']['name']);
$ext1 = substr($image1, strrpos($image1, '.')+1);
$idimg1 = md5(uniqid() . time() . $filename1) . "-1." . $ext1;
$target_file1 = $target_dir . basename($idimg1);
//identify images file
$realImages = imagecreatefromjpeg($target_file1);
$width = imageSX($realImages);
$height = imageSY($realImages);
//save for thumbs size
$thumbWidth = 150;
$thumbHeight = ($thumbWidth / $width) * $height;
//change images size
$thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImage, $realImages, 0,0,0,0, $thumbWidth, $thumbHeight, $width, $height);
//save thumbnail images
imagejpeg($thumbImage,$target_dir."thumb_".$idimg1);
//remove images object from memory
imagedestroy($realImages);
imagedestroy($thumbImage);
?>
Where is wrong?
You're trying to use the original file name (after mangling) as the source for imagecreatefromjpeg(), when you should be using the temporary name assigned by the upload process: $_FILES['txtfile']['tmp_name']
Do this:
$realImages = imagecreatefromjpeg($_FILES['txtfile']['tmp_name']);
You're also not moving the uploaded file to a permanent location. The temporary version will be deleted when your script terminates and the file will be lost.
Note also that your code is doing no error checking whatsoever, so if your upload fails you won't know about it. See the PHP section on Handling File Upload
I applied a filter to the .jpg images of a folder as follows:
$images = glob('images/*.jpg');
foreach($images as $image) {
$image_prefix = "image-beautiful-";
$image = imagecreatefromjpeg($image);
$rand = rand(50, 500);
imagefilter($image, IMG_FILTER_COLORIZE, 75, 15, 10);
$new_image = imagejpeg($image, $image_prefix .$rand.'.jpg');
imagedestroy($image);
}
The generated images save in the main directory. How can I directly save them to another folder like generated-images using PHP?
according to the doco for imagejpg, the second parameter is the path and filename, so try adding the folder to the image prefix:
$image_prefix = "generated-images" . DIRECTORY_SEPARATOR . "image-beautiful-"
I am trying to upload various images into a dynamically created folder on my server, then take each image and resize it while uploading it into the folder as well creating a new image and a new name.. example: image.jpg (original image) and image-resized.jpg (being the thumbnail image).
The thing I can not figure out is how to resize all images. I am not sure if I should put it in a loop. All I need is for each image I upload (could be 5 a time). It loops through and resizes them all and not just a single image. Here is my code any help would be appreciated!
Code to create folders and move picture into those folders:
// Desired folder structure
$structure = './Fotos/'.$newfolder;
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}else{
$placefoldername = mysql_query("INSERT INTO datefolders (FolderDate) VALUES ('$newfolder')") or die(mysql_error());
echo "<div class=\"success\">El folder fue agregado con exito.<input type=\"button\" name=\"close\" value=\"X\" class=\"close\" /></div>";
}}
// ...
}
if(isset($_POST['upload'])){
$FolderDate = $_POST['fecha-folder'];
$FolderName = $_POST['FolderName'];
$hour = $_POST['hour'];
// Desired folder structure
$structure = './Fotos/'.$FolderDate.'/'.$hour.'/'.$FolderName;
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
for($i=0;$i<count($_FILES['fileupload']['name']);$i++) {
$names = $_FILES['fileupload']['name'][$i];
$target_path = "Fotos/".$FolderDate."/".$hour."/".$FolderName."/";
$target_path = $target_path . basename( $_FILES['fileupload']['name'][$i]);
if(move_uploaded_file($_FILES['fileupload']['tmp_name'][$i], $target_path)) {
$success = 1;
Code to create a smaller (resized image) and also place into the already created folder:
$img = $names;
$imgPath = $structure;
function resizeImage($img, $imgPath, $suffix, $by, $quality)
{
//Create a thunbnail image by resizing the picture
// Open the original image.
$original = imagecreatefromjpeg("$imgPath/$img") or die("Error Opening original (<em>$imgPath/$img</em>)");
list($width, $height, $type, $attr) = getimagesize("$imgPath/$img");
// Determine new width and height.
$newWidth = ($width/$by);
$newHeight = ($height/$by);
// Resample the image.
$tempImg = imagecreatetruecolor($newWidth, $newHeight) or die("Cant create temp image");
imagecopyresized($tempImg, $original, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height) or die("Cant resize copy");
// Create the new file name.
$newNameE = explode(".", $img);
$newName = ''. $newNameE[0] .''. $suffix .'.'. $newNameE[1] .'';
// Save the image.
imagejpeg($tempImg, "$imgPath/$newName", $quality) or die("Cant save image");
// Clean up.
imagedestroy($original);
imagedestroy($tempImg);
return true;
}
$resize = resizeImage($img, $imgPath, "-resized", 23, 100);
Why are you defining the function resizeImage in the for loop? It is being redefined every time the loop iterates. This could be part of the problem. Define the function outside the loop and see if that works.
you can try;
when your first image proccess end use imagedestroy() then second image will proccessed.
I use this piece of code to make thumbnails of an uploaded image.
$file = randString().'.jpg';
$uniPath = 'i/u'.$login;
$completePath = $uniPath.'/a/'.$file;
$thumbPath = $uniPath.'/b/'.$file;
if(copy($_FILES['filename']['tmp_name'], $completePath)){
function convertPic($w_dst, $h_dst, $n_img){
$wxh = $w_dst.'x'.$h_dst;
switch($wxh){
case '150x150': $letter = 'b'; break;
case '50x50': $letter = 'c'; break;
default: $letter = 'z';
}
$dbPath = '/i/u1/'.$letter.'/'.$n_img;
$new_img = $_SERVER['DOCUMENT_ROOT'].$dbPath;
$file_src = "img.jpg"; // temporary safe image storage
$img_src = $file_src;
unlink($file_src);
move_uploaded_file($_FILES['filename']['tmp_name'], $file_src);
list($w_src, $h_src, $type) = getimagesize($file_src); // create new dimensions, keeping aspect ratio
$ratio = $w_src/$h_src;
$h_ratio = ($h_dst / $h_src);
$w_ratio = ($w_dst / $w_src);
if($w_src > $h_src){ //landscape
$w_crop = round($w_src * $h_ratio);
$h_crop = $h_dst;
$src_x = ceil(($w_src - $h_src)/2);
$src_y = 0;
}
elseif($w_src < $h_src){ // portrait
$h_crop = round($h_src * $w_ratio);
$w_crop = $w_dst;
$src_y = ceil(($h_src - $w_src)/2);
$src_x = 0;
}
else { //square
$w_crop = $w_dst;
$h_crop = $h_dst;
$src_x = 0;
$src_y = 0;
}
switch ($type)
{case 1: // gif -> jpg
$img_src = imagecreatefromgif($file_src);
break;
case 2: // jpeg -> jpg
$img_src = imagecreatefromjpeg($file_src);
break;
case 3: // png -> jpg
$img_src = imagecreatefrompng($file_src);
break;
}
$img_dst = imagecreatetruecolor($w_dst, $h_dst); // resample
imagecolorallocate($img_dst, 255, 255, 255) or die("fail imagecolorallocate");
imagecopyresampled($img_dst, $img_src, 0, 0, $src_x, $src_y, $w_crop, $h_crop, $w_src, $h_src) or die("imagecopyresampled($img_dst, $img_src, 0, 0, $src_x, $src_y, $w_crop, $h_crop, $w_src, $h_src)");
imagejpeg($img_dst, $new_img); // save new image
unlink($file_src); // clean up image storage
imagedestroy($img_src);
imagedestroy($img_dst);
return $db_path;
}
convertPic(150, 150, $file);
convertPic(250, 250, $file);
But for some reason the convertPic function does not work if called twice as in the example above. If it is called once everything works fine. I've put an alert if imagecopyresampled fails and it outputs
imagecopyresampled(Resource id #17,
img.jpg, 0, 0, 0, 0, 250, 250, , )
I think the problem is with the temporary image storing but not sure. Please help.
It would appear that you're processing an uploaded image. As part of the processing function, you move the uploaded file from its temporary directory, and then do some work on it.
When you call the function again the second time, the uploaded file is not longer in the temporary directory, and things blow up.
function convertPic(...) {
....
move_uploaded_file($_FILES['filename']['tmp_name'], $file_src);
....
unlink($file_src);
....
}
Basically the first call to convertPic processes and then deletes the "source", which means it's no longer available for the second call immediately afterwards.
I guess problem is with unlink($file_src)...
First, you call convertPic() function and it works OK because your img.jpg is still here, then you remove your image with unlink() and try to call again same routine that actually needs this file to work properly.
Also you can't move same file twice, so you have to move it outside the function, do your job as many times as needed, and after that, unlink image. Unlink should be after double-call of convertPic(), and move_uploaded_file() should be before function convertPic().
Well, that's what I think on first sight.
I am trying to generate an image report for a particular items. Every item has a unique item number, which is stored in the variable $pk.
In this, calling up images/$pk.jpg and/or screenshots/$pk.jpg will show the relevant image or screenshot for the current item page. This works fine in the actual page, however not in my popup report.
For one file, I wish to trim it to 800px before outputting, without storing the resultant file.
Additionally, people can upload files, so I am trying to retrieve a list of all files uploaded that end in png, and output each of these to the browser.
Below is my code, however only the html header is output.
What am I doing wrong? Is it a misuse of the imagepng method?
my code:
<?php
if (isset($_GET["pk"])) {
$pk = $_GET["pk"];
}
$con = mysqli_connect("localhost","user","pass", "db");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
} {
echo "<h1>Image report for auction number: ".$pk. "</h1> \n";
$srcName = 'screenshots/'.$pk.'.png';
$info = getimageinfo($srcName);
$src = imagecreatefrompng($srcName);
$dest = imagecreate($info[0], min($info[1], 800));
imagecopy($dest, $src, 0, 0, 0, 0, $info[0], min($info[1], 800));
imagepng($dest);
imagepng('images/'.$pk.'.png');
$filesQuery = "SELECT FILENAME FROM FILES WHERE FILENAME LIKE %png%";
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filename = array(
'FILENAME' => $FILENAME,
);
$files[] = $filename;
}
}
$filesList = '';
foreach ($files as $filenames) {
$imagepng($filenames['FILENAME']);
}
;
}
You cannot mix HTML and PNG output (that is: embed a PNG inside the HTML) as you are trying to do. You need to split this script in two parts.
The first part (e.g. report.php) outputs a list of all the images along with img tags. E.g:
<img src="/thumbnail.php?pk=1234567" />
Then you implement thumbnail.php to output the image (and just the image) along with the appropriate header. E.g:
<?php
$srcName = 'screenshots/'.$_GET['pk'].'.png';
$info = getimageinfo($srcName);
$src = imagecreatefrompng($srcName);
$dest = imagecreate($info[0], min($info[1], 800));
imagecopy($dest, $src, 0, 0, 0, 0, $info[0], min($info[1], 800));
header('Content-type: image/png');
imagepng($dest);
imagedestroy($src);
imagedestroy($dest);
?>
Two remarks on your code:
imagepng() takes an image resource as it's first parameter (a resource, as created with imagecreatefrompng or imagecreate). It does not take a filename as it's first parameter.
Always destroy the images you created with imagedestroy() or you will run out of memory over time (requiring a restart of your webserver).