I am attempting to have a PHP file add an ID to an uploaded image and resave the image. For some reason the code below is not working even though it looks very similar to other examples I have found online. What am I doing wrong?
$productStyle = isset($_POST['productStyle']) ? encodechars($_POST['productStyle']) : "";
$productSize = isset($_POST['productSize']) ? encodechars($_POST['productSize']) : "";
$itemID = isset($_POST['itemID']) ? encodechars($_POST['itemID']) : "";
if ($productStyle!=""){
$fileLocation ='/home/abcdefg/public_html/uploads/'.$productStyle;
$photoLoc = $fileLocation . "/" . $itemID.".png";
if(!is_dir($fileLocation)) {
mkdir($fileLocation , 0777); //create directory if it doesn't exist
}
//add id to image
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
$font = 'Verdana.ttf'; //<-- this file is included in directory
$grey = imagecolorallocate($im, 128, 128, 128);
imagettftext($im, 10, 0, 11, 20, $grey, $font, $itemID);
imagepng($im, $photoLoc); //<-- This does not work
imagedestroy($im);
//move_uploaded_file($_FILES["file"]["tmp_name"], $photoLoc); //<-- This will move the file to the correct folder but without the text added
}
first, move the original file and then remove after watermarking.
$productStyle = isset($_POST['productStyle']) ? encodechars($_POST['productStyle']) : "";
$productSize = isset($_POST['productSize']) ? encodechars($_POST['productSize']) : "";
$itemID = isset($_POST['itemID']) ? encodechars($_POST['itemID']) : "";
if ($productStyle!=""){
$fileLocation ='/home/abcdefg/public_html/uploads/'.$productStyle;
$photoLoc = $fileLocation . "/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
if(!is_dir($fileLocation)) {
mkdir($fileLocation , 0777); //create directory if it doesn't exist
}
//add id to image
$im = imagecreatefrompng($photoLoc);
$font = 'Verdana.ttf'; //<-- this file is included in directory
$grey = imagecolorallocate($im, 128, 128, 128);
imagettftext($im, 10, 0, 11, 20, $grey, $font, $itemID);
imagepng($im, $photoLoc); //<-- This does not work
imagedestroy($im);
unlink($photoLoc);
//move_uploaded_file($_FILES["file"]["tmp_name"], $photoLoc); //<-- This will move the file to the correct folder but without the text added
}
or just change
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
to
$im = imagecreatefrompng($_FILES["file"]["name"]);
here is my code, test1.php works, test2.php not works.
test1.php:
<?php
session_start();
header('Content-type: image/jpeg');
$text = rand(1000,9999);
$font_size = 5;
$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $font_size, 0, 0, $text, $text_color);
$_SESSION['image'] = $image;
$image_session = $_SESSION['image'];
imagejpeg($image_session);
?>
test2.php:
<?php
session_start();
header('Content-type: image/jpeg');
$image_session = $_SESSION['image'];
imagejpeg($image_session);
?>
As you can see, test1.php create a random image.
I can use:
<img src="test1.php">
to show the image from test1.php in any pages.
but, I want to use if else statement in other php files.
for example:
if users click submit button and enter nothing(no answer), the image will still the same, they have to answer the same question. if failed, the image will change.
I don't want to use javascript to prevent users input nothing and store images in disk.
so, I think that I need a variable to store the image that can be used again.
but I found I cannot use above method.
how can I achieve this?
imagecreate() returns a resource representing given image. PHP's sessions cannot store resource-type variables (more precisely - PHP is unable to serialize them upon script end), see http://php.net/manual/en/function.session-register.php:
Note: It is currently impossible to register resource variables in a
session. ...
You may serialize the image to a string and store this string to the session (not tested):
test1.php:
...
ob_start();
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();
$_SESSION['image'] = $contents;
test2.php:
header('Content-type: image/jpeg');
die($_SESSION['image']);
Without knowing much about the context, can't you do something like
session_start();
$_SESSION['randomValue'] = mt_rand(1000,9999);
if(someValueIsEntered){
$_SESSION['randomValue'] = mt_rand(1000,9999);
}
echo "<img src='test.php?random=".$_SESSION['randomValue']."'/>";
Test.php
$randomValue = filter_input(INPUT_GET, 'random');
header('Content-type: image/jpeg');
$text = $randomValue;
$font_size = 5;
$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $font_size, 0, 0, $text, $text_color);
imagejpeg($image);
Multiple parameters example:
Store the information about the image in an array.
session_start();
if(!isset($_SESSION['imageData']){
$_SESSION['imageData'] = array(
"random" => mt_rand(1000,9999),
"x1" => mt_rand(0,10),
"x2" => mt_rand(0,10)
);
}
if(someValueIsEntered){
//Randomize array again.
}
$imageString = "test.php";
foreach ($_SESSION['imageData'] as $key => $value) {
$index = current($array);
if($index == 0) {
$seperator = "?";
} else {
$seperator = "&";
}
$imageString .= $seperator.$key."=".$value;
}
echo "<img src='".$imageString."'/>";
And just call them in the test.php then.
Adding text on images. I have two codes below that works seperately.
The first was used to upload image to a server and database via pdo connection.
The second was used to watermark a stationary image.
My problem is that i want to combine the two codes so as to text watermark an image during upload to Server without the aids
of globle variable.
I have been working on this but cannot get it to work. can someone help me to integrate this. Thanks
<?php
include('pdo.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE) {
echo "That's not an image!";
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],"postphoto/" . $_FILES["image"]["name"]);
$location="postphoto/" . $_FILES["image"]["name"];
$from=$_POST['from'];
$time=time();
$photos='photos';
$statement = $db->prepare('INSERT INTO text_watermark (photo,from_send) values(:photo,:from_send)');
if(!$statement->execute(array(
':photo' => $photos,
':from_send' => $from))){
echo 'There is problem';
}
else{
header("location: lol.php");
exit();
}
}
}
?>
<?php
//Set the Content Type
header('Content-type: image/jpeg');
// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('sunset.jpg');
// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 255, 255, 255);
// Set Path to Font File
$font_path = 'font.TTF';
// Set Text to Be Printed On Image
$text = "This is a sunset!";
// Print Text On Image
imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);
// Send Image to Browser
imagejpeg($jpg_image);
// Clear Memory
imagedestroy($jpg_image);
?>
If your code is correct it's just a case of moving the blocks about. You may want to consider what happens when someone uploads a png. Though you may catch this elsewhere..
<?php
include('pdo.php');
if (!isset($_FILES['image']['tmp_name']))
{
echo "";
}
else
{
$file = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size == FALSE)
{
echo "That's not an image!";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"], "postphoto/" . $_FILES["image"]["name"]);
$location = "postphoto/" . $_FILES["image"]["name"];
//Watermark it!
################
$jpg_image = imagecreatefromjpeg($location);
// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 255, 255, 255);
// Set Path to Font File
$font_path = 'font.TTF';
// Set Text to Be Printed On Image
$text = "This is a sunset!";
// Print Text On Image
imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);
#################
$from = $_POST['from'];
$time = time();
$photos = 'photos';
$statement = $db->prepare('INSERT INTO text_watermark (photo,from_send) values(:photo,:from_send)');
if (!$statement->execute(
array(
':photo' => $photos,
':from_send' => $from
)
)
)
{
echo 'There is problem';
}
else
{
header("location: lol.php");
exit();
}
}
}
if ($jpg_image)
{
//Set the Content Type
header('Content-type: image/jpeg');
// Send Image to Browser
imagejpeg($jpg_image);
// Clear Memory
imagedestroy($jpg_image);
}
?>
Hi i have a form which ask the user to upload photo. is uses the photo as second image(image on top of another) in imagecreatefromjpg and imagecopyresampled. but it seems like the uploaded image is not being get properly. also the default image is not passed from the server when no file is uploaded. im getting these errors:
Warning</b>: imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: Filename cannot be empty in <b>/home/content/52/12096052/html/Testupdate/processor.php</b> on line <b>117</b>
Warning</b>: imagesx() expects parameter 1 to be resource, boolean given in <b>/home/content/52/12096052/html/Testupdate/processor.php</b> on line <b>145</b><br />
Warning</b>: imagesy() expects parameter 1 to be resource, boolean given in /home/content/52/12096052/html/Testupdate/processor.php</b> on line <b>145</b><br />
<b>Warning</b>: imagecopyresampled() expects parameter 2 to be resource, boolean given in /home/content/52/12096052/html/Testupdate/processor.php</b> on line <b>145</b><br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/content/52/12096052/html/Testupdate/processor.php:117) in <b>/home/content/52/12096052/html/Testupdate/processor.php</b> on line <b>186</b><br />
this is my code processor.php:
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded files //i made it as the same directory where the .php file is
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self;
// make a note of the location of the upload form in case we need it
$uploadForm = 'https://' . $_SERVER['HTTP_HOST'] . $directory_self . 'index.php';
// name of the fieldname used for the file in the HTML form
$fieldname = 'file';
// check the upload form was actually submitted else print form
if(isset($_POST['submit']))
{
if($_FILES['file']['tmp_name']!="")
{
$allowedExts = array("jpeg", "jpg");
$temp = explode(".", $_FILES['file']['name']);
$extension = end($temp);
$notallowedExts = array("png", "gif", "pdf", "doc", "docx", "txt", "html", "xlsx", "mov");
$nottemp = explode(".", $_FILES['file']['name']);
$notextension = end($nottemp);
if ((($_FILES['file']['type'] == "image/jpeg") || ($_FILES['file']['type'] == "image/jpg")) && ($_FILES['file']['size'] < 1300000) && in_array($extension, $allowedExts))
{
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename);
}
elseif(($_FILES['file']['size'] > 1300000)||(in_array($notextension, $notallowedExts)))
{
echo '<script type="text/javascript">';
echo 'alert("Invalid file upload. Please check your input.");';
echo 'window.location.href = "index.php";';
echo '</script>';
die();
}
}
else
{
$uploadFilename = "def_img.jpg";
}
}
//for textbox input
$name = $_POST['name'];
$email = $_POST['email'];
$office_id = $_POST['office_id'];
$var_title = $_POST['title'];
$var_story = $_POST['story'];
$var_task = $_POST['task'];
$var_power = $_POST['power'];
$var_solve = $_POST['solve'];
$var_result = $_POST['result'];
$get_title = $_POST['title'];
$title = strtoupper ($get_title);
$namehere = "Super Story By " .$_POST['name'];
$story = "My super story begins with " . $_POST['story'] . " My task was " . $_POST['task'] ." With the super power of ". $_POST['power'] ." I solved it by ". $_POST['solve'] ." The result was ". $_POST['result'];
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
header('Content-Type: image/jpeg');
$imagename = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($imagename);
$black = imagecolorallocate($im, 0, 0, 0);
$font = 'arialbi.ttf';
$font2 = 'ariali.ttf';
$newtitle = wordwrap($title, 24, "\n", true);
$newertitle = explode("\n", $newtitle);
imagettftext($im, 33, 0, 8, 270, $black, $font, $newertitle[0]);
imagettftext($im, 33, 0, 8, 320, $black, $font, $newertitle[1]);
imagettftext($im, 12, 0, 283, 365, $black, $font, $namehere);
$newtext = wordwrap($story, 50, "\n", true);
$newertext = explode("\n", $newtext);
imagettftext($im, 10, 0, 283, 385, $black, $font2, $newertext[0]);
imagettftext($im, 10, 0, 283, 400, $black, $font2, $newertext[1]);
imagettftext($im, 10, 0, 283, 415, $black, $font2, $newertext[2]);
imagettftext($im, 10, 0, 283, 430, $black, $font2, $newertext[3]);
imagettftext($im, 10, 0, 283, 445, $black, $font2, $newertext[4]);
imagettftext($im, 10, 0, 283, 460, $black, $font2, $newertext[5]);
imagettftext($im, 10, 0, 283, 475, $black, $font2, $newertext[6]);
imagettftext($im, 10, 0, 283, 490, $black, $font2, $newertext[7]);
imagettftext($im, 10, 0, 283, 505, $black, $font2, $newertext[8]);
imagettftext($im, 10, 0, 283, 520, $black, $font2, $newertext[9]);
imagettftext($im, 10, 0, 283, 535, $black, $font2, $newertext[10]);
imagecopyresampled($im, $img2, 10, 350, 0, 0, 263, 175, imagesx($img2), imagesy($img2));
$date_created = date("YmdHis");//get date created
$img_name = "-img_entry.jpg"; //the file name of the generated image
$img_newname = $date_created . $img_name; //datecreated+name
$img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save the image
imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality
$newpath = "/home/content/52/12096052/html/Testupdate/image_entry/";
$newdir = $newpath.$img_newname;
copy ($img_dir, $newdir);
$http_dir = 'https://www.uaewebdeveloper.com/Testupdate/image_entry/';
$post_link = $http_dir . $img_newname;
$msg = 'Super Story by ';
$post_msg = $msg.$name;
imagedestroy($im);
}
else{
echo '<script type="text/javascript">';
echo 'window.alert("*All fields required.");';
echo 'window.location.href = "index.php";';
echo '</script>';
}
//get time to save in db
$sql_date = date("Y/m/d H:i:s");
//save inputs to db
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($story)) {
$save_sql = mysql_query("INSERT INTO `tbl_amatest` (filename, name, email, office_id, title, story, time) VALUES ('$img_newname','$name','$email','$office_id','$title','$story','$sql_date')");
header('Location:' .'success.html');
mysql_close($con);
}
when i specify the second image as the dafault, it works. but it's getting the only the default not the uploaded when someone uploads a file. so basically, i have two problems here:
the uploaded image is not being passed/uploaded properly
the default image is not being get from the server properly
please help me. i dont know what to do. i have read posts, almost the same but it didn't help me. thanks a lot in advance!
Try to do the major two change in your code :
Replace code if(isset($_FILES['file']['tmp_name'])){
With if($_FILES['file']['tmp_name']!=""){
Remove path from default image : $uploadFilename = 'def_img.jpg';
I have tried its working fine. The complete code by which i have test that default image and uploaded image both available for further processing.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded files //i made it as the same directory where the .php file is
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self;
#echo "$uploadsDirectory<br>";
#exit;
$fieldname = 'file';
if(isset($_POST['submit']))
{
if($_FILES['file']['tmp_name']!="")
{
$allowedExts = array("jpeg", "jpg");
$temp = explode(".", $_FILES['file']['name']);
$extension = end($temp);
$notallowedExts = array("png", "gif", "pdf", "doc", "docx", "txt", "html", "xlsx", "mov");
$nottemp = explode(".", $_FILES['file']['name']);
$notextension = end($nottemp);
if ((($_FILES['file']['type'] == "image/jpeg") || ($_FILES['file']['type'] == "image/jpg")) && ($_FILES['file']['size'] < 1300000) && in_array($extension, $allowedExts))
{
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename);
}
elseif(($_FILES['file']['size'] > 1300000)||(in_array($notextension, $notallowedExts)))
{
echo '<script type="text/javascript">';
echo 'alert("Invalid file upload. Please check your input.");';
echo 'window.location.href = "index.php";';
echo '</script>';
die();
}
}
else
{
$uploadFilename = "images.jpg";
}
}
/*$get_title = $_POST['title'];
$story = "My super story begins with " . $_POST['story'] . " My task was " . $_POST['task'] ." With the super power of ". $_POST['power'] ." I solved it by ". $_POST['solve'] ." The result was ". $_POST['result'];
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
*/
echo " FILE : $uploadFilename";
//header('Content-Type: image/jpeg');
$upload = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($upload);
$black = imagecolorallocate($im, 0, 0, 0);
$font = 'arialbi.ttf';
$font2 = 'ariali.ttf';
$newtitle = wordwrap($title, 24, "\n", true);
$newertitle = explode("\n", $newtitle);
imagettftext($im, 33, 0, 8, 270, $black, $font, $newertitle[0]);
imagettftext($im, 33, 0, 8, 320, $black, $font, $newertitle[1]);
imagettftext($im, 12, 0, 283, 365, $black, $font, $namehere);
$newtext = wordwrap($story, 50, "\n", true);
$newertext = explode("\n", $newtext);
imagettftext($im, 10, 0, 283, 385, $black, $font2, $newertext[0]);
imagettftext($im, 10, 0, 283, 400, $black, $font2, $newertext[1]);
imagecopyresampled($im, $img2, 10, 350, 0, 0, 263, 175, imagesx($img2), imagesy($img2));
$date_created = date("YmdHis");//get date created
$img_name = "-img_entry.jpg"; //the file name of the generated image
$img_newname = $date_created . $img_name; //datecreated+name
$img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save the image
imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality
$newpath = "/home/content/52/12096052/html/Testupdate/image_entry/";
$newdir = $newpath.$img_newname;
copy ($img_dir, $newdir); //copy to new folder
$http_dir = 'https://www.uaewebdeveloper.com/Testupdate/image_entry/';
$post_link = $http_dir . $img_newname;
$msg = 'Super Story by ';
$post_msg = $msg.$name;
imagedestroy($im);
//}
I want to make an image "onfly" with some text. Is it possible with php? I am trying with this one but no output is coming can anyone watch my code please?
function createCaptcha($string){
$image = PATH_DIR . "blueprint/images/bg6.png";
$text_vertical_position = 97;
$font_size = 15;
$color = '32a53d';
Header ("Content-type: image/png");
$color = convert_to_rgb($color);
$info = GetImageSize($image);
$width = $info[0];
$height = $info[1];
if (preg_match("/.gif/", $image)) {
$image = imageCreateFromGif($image);
} elseif (preg_match("/.png/", $image)) {
$image = imageCreateFromPng($image);
} elseif (preg_match("/.jpg/", $image)) {
$image = imageCreateFromJpeg($image);
} elseif (preg_match("/.jpeg/", $image)) {
$image = imageCreateFromJpeg($image);
}
$imgcolor = ImageColorAllocate ($image, $color[0], $color[1], $color[2] );
imagettftext($image, $font_size, 0, $start_length, $text_vertical_position,
$imgcolor, $font , $text);
ImagePNG ($image);
ImageDestroy ($image);
}
I am using codeigniter to make it.
Thank You
It seems you made a mistake in parameter of the function: $string not $text
imagettftext($image, $font_size, 0, $start_length, $text_vertical_position,
$imgcolor, $font, $string);
PS. If you make captcha - it would not reliable without any additional distortion of the image.
Why not to use ready-made solutions?
http://www.phpcaptcha.org/
http://www.captcha.ru/kcaptcha/