Warning : imagecreatefromjpeg()expects parameter 1 to be resource - php

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

Related

How to save same image with different names in PHP?

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.

Php Image creation and upload to folder

I want to create a image dynamically and upload it to a folder. I will be getting image for body,sleeve,collar and cuff dynamically from user selection. I am merging all these images to create a new image and this new image to uploaded in a folder. Am not able to upload the filename to folder and there is no errors displaying also but am able to generate the merged image.
Below is code,
<?php
$body = "img1.jpg";
$sleeve = "img2.jpg";
$collar = "img3.jpg";
$cuff = "img4.jpg";
$outputImage = imagecreatetruecolor(800, 800);
$background = imagecolorallocate($outputImage, 0, 0, 0);
imagecolortransparent($outputImage, $background);
$white = imagecolorallocate($outputImage, 255, 255, 255);
imagefill($outputImage, 0, 0, $white);
$first = imagecreatefrompng($body);
$second = imagecreatefrompng($sleeve);
$third = imagecreatefrompng($collar);
$fourth = imagecreatefrompng($cuff);
imagecopyresized($outputImage,$first,0,0,0,0,600,600,600,600);
imagecopyresized($outputImage,$second,0,0,0,0,600,600,600,600);
imagecopyresized($outputImage,$third,0,0,0,0, 600, 600, 600, 600);
imagecopyresized($outputImage,$fourth,0,0,0,0,600,600,600,600);
$filename = round(microtime(true)).'.png';
imagepng($outputImage, $filename);
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
$ret = move_uploaded_file($filename, DIR_IMAGE.$filename);
print_r(error_get_last());
if($ret)
{
echo "success";die;
}
else
{
echo "fail";die;
}
imagedestroy($outputImage);
?>echo "fail";die;
}
imagedestroy($outputImage);
?>
move_uploaded_file won't work on $filename because it's not an uploaded file - it was just created by your code.
Try switching the two lines (like below) and adding your path:
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
imagepng($outputImage, DIR_IMAGE . $filename);
And remove the move_uploaded_file line:
//$ret = move_uploaded_file($filename, DIR_IMAGE.$filename);
you are using imagepng(), That saves file to particular location you are providing.
Syntax for imagepng() :
bool imagepng ( resource $image [, mixed $to [, int $quality [, int $filters ]]] )
where $to refers to location where you want to save your image (including filename).
So instead of
$filename = round(microtime(true)).'.png';
imagepng($outputImage, $filename);
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
$ret = move_uploaded_file($filename, DIR_IMAGE.$filename);
Try This,
$filename = round(microtime(true)).'.png';
define('DIR_IMAGE', '/opt/lampp/htdocs/dutees/image/design-uploads/');
imagepng($outputImage, DIR_IMAGE.$filename);
You don't need move_uploaded_file() anymore, because the image created is already in your server.
I also had similar problem while creating captcha for new users, and This solution worked.
You should try file_put_contents instead of move_uploaded_file.
file_put_contents('you_file_location/filename', IMAGE_OBJECT_HERE);
or you can also save file using fwrite function.

Resize copied image on upload as thumbnail

I am working on an uploader and slowly getting it working, I am uploading 3 images at once, and setting arrays for each one as keys, with an increment of ++1. I am wanting to resize the image before it gets copied to the thumbnail folder.
I have this code.
Everything works with it.
As you see, I started on getting the file info, but after that I am totally stuck on what to do after to resize the image proportionally with a maximum width of xpx and height to match it without looking distorted.
Any help would be really appreciated. Thank You.
EDIT --- I started working on it myself and wondering if this is the right approach to what i am doing.
<?php
if (isset($_POST['addpart'])) {
$image = $_FILES['images']['tmp_name'];
$name = $_POST['username'];
$i = 0;
foreach ($image as $key) {
$fileData = pathinfo(basename($_FILES["images"]["name"][$i]));
$fileName[] = $name . '_' . uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . end($fileName));
copy("image/" . end($fileName), "image_thumbnail/" . end($fileName));
// START -- THE RESIZER THAT IS BEING WORKED ON
$source = "image_thumb/" . end($fileName);
$dest = "image_thumb/" . end($fileName);
$quality = 100;
$scale = 1 / 2;
$imsize = getimagesize($source);
$x = $scale * $imsize[0];
$y = $scale * $imsize[1];
$im = imagecreatefromjpeg($source);
$newim = imagecreatetruecolor($x, $y);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $x, $y, $imsize[0], $imsize[1]);
imagejpeg($newim, $dest, $quality);
// END -- THE RESIZER THAT IS BEING WORKED ON
$i++;
}
echo 'Uploaded<br>';
echo 'Main Image - ' . $fileName[0] . '<br>';
echo 'Extra Image 1 - ' . $fileName[1] . '<br>';
echo 'Extra Image 2 - ' . $fileName[2] . '<br>';
echo '<hr>';
}
?>
thanks
Use GD library.
Create input image object using imagecreatefromstring() for example: imagecreatefromstring(file_get_contents($_FILES['images']['tmp_name'][$i]))
It's the simplest way.
Another option is to detect file type and use functions like imagecreatefromjpeg (), imagecreatefrompng(), etc.
Create output empty image using imagecreate()
Use imagecopyresampled() or imagecopyresized() to resize image and copy+paste it from input image to output image
Save output image using function like imagejpeg()
Clean memory using imagedestroy()
The built-in image manipulation commands of PHP makes your code difficult to understand and to maintain. I suggest you to use a library which wraps it into a more productive way.
If you use Intervention/image, for example, your code will look like this:
<?php
// target file to manipulate
$filename = $_FILES['images']['tmp_name'];
// create image instance
$img = Image::make($filename);
// resize to width, height
$img->resize(320, 240);
// save it!
$img->save('thumbs/'. uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION));
Read the full documentation here: http://image.intervention.io/use/uploads

Can not resize multiple images in PHP

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.

PHP GD Image Cropping Function

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.

Categories