I am following this tutorial: Tutorial
In the PHP script it uses the GD library to move and save files.
This script is working fine when i am using it on my local WAMP server.
But when I upload it to my hosting on YourHosting it does not, When i use a JPEG or PNG file it works but when I use a .JPG file it does not work.
This is part of the code:
$sTempFileNameFirst = TEMPLATEPATH;
$sTempFileNameFirstSrc = get_bloginfo('template_directory');
$sTempFileNameLast = '/cache/' . md5(time().rand());
$sTempFileName = $sTempFileNameFirst . $sTempFileNameLast;
$sTempFileNameSrc = $sTempFileNameFirstSrc . $sTempFileNameLast;
// move uploaded file into cache folder
move_uploaded_file($_FILES['upload-image']['tmp_name'], $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
echo("jpg");
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
echo("unlink");
return;
}
echo("before truecolor");
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight ) or die ("can't open gd stream");
echo("after imagetruecolor");
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['width'], (int)$_POST['height']);
echo("after resample");
// define a result image filename
//$sResultFileName = $sTempFileName . $sExt;
$sResultFileNameSrc = $sTempFileNameSrc . $sExt;
echo($sResultFileNameSrc);
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileNameSrc;
As you can see I use echo to see where it works and where it does not. So for JPEG and PNG files every code works, but whenever i use a JPG file the echo before #imagecreatetruecolor works but after does not work. So the problem is that that function does not execute. Also the "or die" part after the function does not work.
What could be the problem?
PHPINFO() says GD info is enabled and has bundled version(2.1.0)
Related
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.
The script is constructed like this:
// Function For Image Upload
public function storeUploadedImage($image) {
if ($image['error'] == UPLOAD_ERR_OK) {
// Does the Document object have an ID?
if (is_null($this->id))
trigger_error("Document::storeUploadedImage(): Attempt to upload an image for an Document object that does not have its ID property set.", E_USER_ERROR);
// Delete any previous image(s) for this Document
$this->deleteImages();
// Get and store the image filename extension
$this->imgExtension = strtolower(strrchr($image['name'], '.'));
// Store the image
$tempFilename = trim($image['tmp_name']);
if (is_uploaded_file ($tempFilename)) {
if (!(move_uploaded_file($tempFilename, $this->getImagePath())))
trigger_error("Document::storeUploadedImage(): Couldn't move uploaded file.", E_USER_ERROR);
if (!(chmod($this->getImagePath(), 0666)))
trigger_error("Document::storeUploadedImage(): Couldn't set permissions on uploaded file.", E_USER_ERROR);}
// Get the image size and type/Extension
$attrs = getimagesize ($this->getImagePath());
$imageWidth = $attrs[0];
$imageHeight = $attrs[1];
$imageType = $attrs[2];
// Load the image into memory
switch ($imageType) {
case IMAGETYPE_GIF:
$imageResource = imagecreatefromgif ($this->getImagePath());
break;
case IMAGETYPE_JPEG:
$imageResource = imagecreatefromjpeg ($this->getImagePath());
break;
case IMAGETYPE_PNG:
$imageResource = imagecreatefrompng ($this->getImagePath());
break;
default:
trigger_error ("Document::storeUploadedImage(): Unhandled or unknown image type ($imageType)", E_USER_ERROR);
}
// Copy And Resize The Image To Create The Thumbnail
$thumbHeight = intval ($imageHeight / $imageWidth * 120);
$thumbResource = imagecreatetruecolor (120, $thumbHeight);
imagecopyresampled($thumbResource, $imageResource, 0, 0, 0, 0, 120, $thumbHeight, $imageWidth, $imageHeight);
// Save the Image thumbnail
switch ($imageType) {
case IMAGETYPE_GIF:
imagegif ($thumbResource, $this->getImagePath("thumb"));
break;
case IMAGETYPE_JPEG:
imagejpeg ($thumbResource, $this->getImagePath("thumb"), 85);
break;
case IMAGETYPE_PNG:
imagepng ($thumbResource, $this->getImagePath("thumb"));
break;
default:
trigger_error ("Document::storeUploadedImage(): Unhandled or unknown image type ($imageType)", E_USER_ERROR);
}
$this->update();
}
}
// Funcion To Get The Relative Path To The Article's Fullsize Image
public function getImagePath($type="fullsize") {
return ($this->id && $this->imgExtension) ? ("/images" . "/$type/" . $this->id . $this->imgExtension) : false;
}
This is the form input field:
<input type="file" name="image" id="image" placeholder="Choose an image to upload" maxlength="255"/>
The rest of the inputs store to the MySQL database table. No error is showing for the upload. The image isn't uploading to the designated directory which is defined in a configuration file which is required in this script
Unfortunately I can't post comments yet, so I'm writing this as an answer.
You check whether image was uploaded correctly and work with it, but the function does nothing otherwise. Then you check if file was uploaded properly with is_uploaded_file and if it wasn't... you continue your routine. It would be wiser to throw an exception, like you're doing in other places.
Do you have error reporting level set on reasonable level (so you would know what's going wrong)?
I am working on project its about gemstone where I make admin panel where user can upload images am trying to resize the images it work some how but it give me black output in given dir where I am uploading .
Here is my code .
$target_path = SITE_ROOT .DS. $this->upload_dir .DS. $this->filename;
// Make sure a file doesn't already exist in the target location
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
// i am trying to resize the image
if( copy ($this->temp_path,$this->filename) or die ("Could not copy")){
$imagefile=$this->filename;
list($width, $height) = getimagesize($this->filename);
$image_p = imagecreatetruecolor($this->new_width,$this->new_height);
if ($this->type =='jpg')
{
$img = imagecreatefromgif($imagefile);
imagecopyresampled($image_p, $img, 0, 0, 0, 0, $this->new_width,$this->new_height, $width, $height);
imagegif($image_p,$target_path);
}
else{ echo 'something went wrongs';}
}
// Attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)) {
// Success
// Save a corresponding entry to the database
if($this->create()) {
// We are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
// File was not moved.
$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
return false;
}
First of all change the imagecopyresampled function to imagecopyresized function.
imagecopyresized($image_p, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height);
Than change the function from imagecreatefromgif to imagecreatefromjpeg because you are using jpg in if condition.And write the path below i have given like that.
move_uploaded_file($this->temp_path, imagejpeg($image_p,$target_path,100));
And sure to unlink if you don't than it will bring you two image files because you are using copy function be sure to unlink.
unlink($this->filename);
I have just done it. I hope it will work for you too.
I had the below code that load image from DB. There are more than 600 rows of image has been inserted into the DB. I need the script that can perform these action:
Step 1) Load the image from DB
Step 2) process the image by putting the watermark
Step 3) Output the image to the browser.
I had the below code, that load and show the image. but I don't have any idea how to do the watermark.
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT type,content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$contenttype = #mysql_result($result,0,"type");
$image = #mysql_result($result,0,"content");
header("Content-type: $contenttype");
echo $image;
mysql_close($dbconn);
?>
Please help...
You could ether learn how to manipulate images on your own from php.net or you just get a package like the one below:
http://pear.php.net/package/Image_Tools
(Tools collection of common image manipulations. Available extensions are Blend, Border, Marquee, Mask, Swap, Thumbnail and Watermark.)
How about calling your image the same way you do for the SELECT type, content?
Select the image with an imagepath from your database and then style it so it floats over your information. you could also hardcode the watermark image as it is always the same image you can have repeated. You won't see your information but if you put an opacity on the image, you can see through it:
#img.watermark {
float:left;
opacity:0.1;
z-index:1;
}
This is just one idea on how to do it, but should work quite nicely!
take a look at
imagecopymerge()
from php's graphics librabry, it should do what you're looking for.
http://www.php.net/manual/en/function.imagecopymerge.php
Finally I get the solution, here is the code:
<?php
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT id, original_name, type, content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$fileID = #mysql_result($result,0,"id");
$contenttype = #mysql_result($result,0,"type");
$filename = #mysql_result($result,0,"original_name");
$image = #mysql_result($result,0,"content");
$fileXtension = pathinfo($filename, PATHINFO_EXTENSION);
$finalFileName = $fileID.".".$fileXtension;
// put the file on temporary folder
$filePutPath = "/your/temporary/folder/".$finalFileName;
// put the contents onto file system
file_put_contents($filePutPath, $image);
// get the watermark image
$stamp = imagecreatefrompng('../images/watermark.png');
switch($fileXtension)
{
case 'JPEG':
case 'JPG' :
case 'jpg' :
case 'jpeg':
$im = imagecreatefromjpeg($filePutPath);
break;
case 'gif' :
case 'GIF' :
$im = imagecreatefromgif($filePutPath);
break;
case 'png' :
case 'PNG' :
$im = imagecreatefromgif($filePutPath);
break;
default :
break;
}
list($width, $height) = getimagesize($filePutPath);
// set area for the watermark to be repeated
imagecreatetruecolor($width, $height);
// Set the tile (Combine the source image and the watermark image together)
imagesettile($im, $stamp);
// Make the watermark repeat the area
imagefilledrectangle($im, 0, 0, $width, $height, IMG_COLOR_TILED);
header("Content-type: $contenttype");
// free the memory
imagejpeg($im);
imagedestroy($im);
// delete the file on temporary folder
unlink($filePutPath);
mysql_close($dbconn);
?>
For the life of me, I cant figure out how to code part of this process:
Ive Already Completed These Steps:
1. Upload ZIP archive (containing only photos in gif, png, and jpg)
2. Unpack to folder
3. Scan folder for filenames + file extentions
I Need Help With:
4. Convert only PNG to JPG
Any help would be appreciated!
Brandon
EDIT:
Does this make sense?
$directory = "../images/ilike/goldfish/";
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$pic = imagecreatefrompng($directory);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $pic, 0, 0, 0, 0, imagesx($image), imagesy($image))
imagedestroy($image);
imagejpeg($bg, $image . ".jpg", 100);
ImageDestroy($bg);
}
Take in the file from a form as usual, open it with http://www.php.net/manual/en/class.ziparchive.php and use http://www.php.net/manual/en/ziparchive.extractto.php to extract the files to an empty folder. Then using the PHP standard file handling functions scan filenames that end with .jpg. Load them in with http://www.php.net/manual/en/function.imagecreatefromjpeg.php and then save them out with http://www.php.net/manual/en/function.imagepng.php .
//here we create directory
----------------------------
$new_folder=mkdir('C:\\wamp\\www\\TestImage\\uploads\\'.$folder_name, 0777, true);
$path="uploads\\".$folder_name."\\";
//uploading files
-----------------------------
$fileName = $_FILES["upload_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["upload_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = #$_FILES["upload_file"]["application/zip"]; // The type of file it is
$fileSize = $_FILES["upload_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["upload_file"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".",$_FILES["upload_file"]["name"]); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!preg_match("/.(zip)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
//echo "ERROR: Your file was not .zip file";
echo "Please select image files.Supported format are .Zip</br>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
#exit();
}
//unzip to specific location
--------------------------------
if(preg_match("/.(zip)$/i", $fileName))
{
$moveResult= move_uploaded_file($fileTmpLoc, $fileName);
if($moveResult == true)
{
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);
$zip->close();
} else {
echo 'failed';
}
}
unlink($fileName); // Remove the uploaded file from the PHP temp folder
//exit();
}
//function for Convert only PNG to JPG
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);//$outputFile->define name of output file and $quality is a number between 0 (best compression) and 100 (best quality)
imagedestroy($image);
note->refer for <gdlib> http://www.php.net/manual/en/function.imagejpeg.php