PHP Add text to image and save - php

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"]);

Related

Save image as file in a folder on the server

I have this code running...
$im = imagecreatefromstring($arr['IMAGE']->load());
$result = $arr['IMAGE']->load();
echo $result;
exit();
and this code is showing the image on the browser. My question is...how to save as a file and save on the server?
I am using this code and it is saving as a file but there isn't a image.
define('UPLOAD_DIR', 'testuploads/');
// $img = str_replace('data:image/png;base64,', '', $result);
// $img = str_replace(' ', '+', $img);
$data = imagejpeg($result);
$file = UPLOAD_DIR . uniqid() . '.jpeg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
use imagejpeg($result, $file) or imagepng if it is a png, instead of file_put_contents.
(where $result is your img, and $file your path+file name)
EDIT: see doc: http://php.net/manual/en/function.imagejpeg.php
example:
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');
?>

unable to show text on the image

I want to show some text on an image. I am using the following code :
session_start();
$name = $_SESSION['name'];
$nameLength = strlen($name); // gets the length of the name
$randomNumber = rand(0, $nameLength - 1); // generates a random number no longer than the name length
$string = ucfirst(substr($name, $randomNumber, 1)); // gets the substring of one letter based on that random number
$im = imagecreatefromjpeg("love.jpg");
$text = " First Letter of Your partner's name is";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);
$black1 = imagecolorallocate($im, 255, 0, 0);
imagettftext($im, 32, 0, 380, 430, $black, $font, $text);
imagettftext($im, 52, 0, 630, 530, $black1, $font, $string);
imagejpeg($im, null, 90);
but on localhost this code is showing the text on the image but when I am uploading it to server then it is showing only image, text is not shown on this image ? what may be the problem?
$_SESSION['name'] is value when I login to facebook and save the name of the user into $_SESSION
I have uploaded the above code on the server :
http://rohitashvsinghal.com/fb/login.php
The font must exist in the location specified obviously and the fullpath to the font works best in my experience.
<?php
session_start();
$name = $_SESSION['name'];
$nameLength = strlen($name);
$randomNumber = rand(0, $nameLength - 1);
$string = ucfirst(substr($name, $randomNumber, 1));
$im = imagecreatefromjpeg("love.jpg");
$text = " First Letter of Your partner's name is";
/* Either use the fullpath or the method given below from the manual */
$fontpath=$_SERVER['DOCUMENT_ROOT'].'/path/to/fonts/';
putenv('GDFONTPATH='.realpath( $fontpath ) );
$fontname='arial.ttf';
$font = realpath( $fontpath . DIRECTORY_SEPARATOR . $fontname );
$black = imagecolorallocate($im, 0, 0, 0);
$black1 = imagecolorallocate($im, 255, 0, 0);
imagettftext($im, 32, 0, 380, 430, $black, $font, $text);
imagettftext($im, 52, 0, 630, 530, $black1, $font, $string);
imagejpeg($im, null, 90);
?>
However, the manual states:-
Depending on which version of the GD library PHP is using, when
fontfile does not begin with a leading / then .ttf will be appended to
the filename and the library will attempt to search for that filename
along a library-defined font path.
In many cases where a font resides in the same directory as the script
using it the following trick will alleviate any include problems.
<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

PHP gd create image, add to folder and db

I have created this image:
header('content-type: image/jpeg');
//Load our base image
$image = imagecreatefrompng(BASEPATH . '../images/blogMainImage.png');
//Setup colors and font file
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$font_path = BASEPATH . '../fonts/ACME Explosive.ttf';
//Get the positions of the text string
$text = wordwrap($_POST['title'], 15, "\n");
//Create Month
imagettftext($image, 16, 0, 20, 40, $black, $font_path, $text);
//Create final image
imagejpeg($image, '', 100);
//Clear up memory;
imagedestroy($image);
I have successfully created the image. Now what i need to do is to get the created image filename, save the filename to db and file to a upload folder..
Is it possible?
Thanks.
This is probably what you need:
$name ='myimage.png';
// make sure you create a folder called **images** in the directory where the script is and give it write permissions.
$save_path = realpath(dirname(__FILE__).'/images/'.$name);
// I assume that you want to use the image in a website.
$imageurl = "http://www.mysite.com/images/$name";
imagejpeg($im, $save_path); // saves the image to **this_dir/images/myimage.png**
imagedestroy($im);
in regards to store the filename in a db, you'll need to set the the database first and then use something like this:
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Photos(save_path, imageurl)
VALUES ("$save_path", "$imageurl")");
mysqli_close($con);
I think you can also add this codes:
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE lms_users SET userPic='$actual_image_name' WHERE userId='$_SESSION[email]'");
}
else
echo "failed";
you need a name and a route to save the image:
// Save the image as 'test.jpg'
$name_image="test.jpg";
imagejpeg($im, 'folder_to_save_image/'.$name_image);
and you can save the name in your data base
check imagejpeg

How to resize an uploded image before using it in an imagecreatefromjpeg function?

I have a code that allows file upload and some text input. It uses the uploaded file in an imagacreatefromjepg and imagecopymerge. I want to resize the uploaded file to a definite size which is 255x175. how can i make it? Here is what is have:
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
// now let's move the file to its final and allocate it with the new filename
#move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
or error('receiving directory insuffiecient permission', $uploadForm);
$upload = $uploadFilename;
$im = imagecreatefromjpeg("bg.jpg");
$img2 = imagecreatefromjpeg($upload);
$black = imagecolorallocate($im, 0, 0, 0);
$font = 'arialbi.ttf';
$font2 = 'ariali.ttf';
imagettftext($im, 24, 0, 50, 280, $black, $font, $title);
imagettftext($im, 10, 0, 320, 362, $black, $font, $namehere);
imagecopymerge($im, $img2, 30, 350, 0, 0, imagesx($img2), imagesy($img2), 100);
$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 = "/home3/site/public_html/mainfolder/image_entry/";//path to another folder
$newdir = $newpath.$img_newname;
copy ($img_dir, $newdir); //copy to new folder
imagedestroy($im);
Hope you can help me fix this. I have raed the posts Resize image before uploading PHP and Php resize width fix. But I dont know how to apply it in my case. Thanks for any and all help.
just after: imagecopymerge($im,... line
$mini_width = ...;// calculate desirable width
$mini_height = ...;// calculate desirable height
$mini_img = #ImageCreateTrueColor($mini_width, $mini_height);
imagecopyresampled($mini_img, $img2, 0, 0, 0, 0, $mini_width, $mini_height, imagesx($img2), imagesy($img2));
next line is $date_created = date(...
change imagejpeg($im, $img_dir , 80); to:
imagejpeg($mini_img, $img_dir , 80);
and finally change imagedestroy($im); to imagedestroy($mini_img);
Actually, you can, but not have to call imagedestroy() for all the resource images created above.

Add text over an image when uploading it in PHP

I have a pictures website like Quickmeme.com and I would like to add text over images.
I currently let the user upload the picture manually, writing the comments with Paint program in Windows which is a bad idea and I need help ...
here is the code I use for Uploading an image, I am thinking of adding a text field below the upload field so what ever the user writes in that box will be printed on the image as an imagetext ... So how can I do that with php?
<?php if(isset($_POST["upload"])){
$tmp_name = $_FILES["file"]["tmp_name"];
$file_name = basename($_FILES["file"]["name"]);
$random = rand(1, 9999999999);
$directory = "Uploads/" . $random . $file_name;
$time = strftime("%H:%M:%S", time());
$date = strftime("%Y-%m-%d", time());
if(move_uploaded_file($tmp_name, $directory)){
if(mysql_query("")){
$query = mysql_query(""); $fetch = mysql_fetch_array($query);
if(mysql_query("")){
header("Location: index.php");
exit;
}
}
}
} ?>
Here is my website http://www.picturepunches.net
You can try
if (isset($_POST["upload"])) {
$tmp_name = $_FILES["file"]["tmp_name"];
$file_name = basename($_FILES["file"]["name"]);
$random = rand(1, 9999999999);
$directory = "Uploads/" . $random . $file_name;
$time = strftime("%H:%M:%S", time());
$date = strftime("%Y-%m-%d", time());
switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
case "jpg" :
$im = imagecreatefromjpeg($_FILES["file"]["tmp_name"]);
break;
case "gif" :
$im = imagecreatefromgif($_FILES["file"]["tmp_name"]);
break;
case "png" :
$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
break;
default :
trigger_error("Error Bad Extention");
exit();
break;
}
$font = 'verdana.ttf';
$grey = imagecolorallocate($im, 128, 128, 128);
$red = imagecolorallocate($im, 255, 0, 0);
// Add some shadow to the text
imagettftext($im, 10, 0, 11, 20, $grey, $font, $date);
imagettftext($im, 10, 0, 10, 35, $grey, $font, $time);
imagettftext($im, 10, 0, 10, 50, $red, $font, $random);
// imagepng($im);
imagedestroy($im);
if (move_uploaded_file($tmp_name, $directory)) {
if (mysql_query("")) {
$query = mysql_query("");
$fetch = mysql_fetch_array($query);
if (mysql_query("")) {
header("Location: index.php");
exit();
}
}
}
}
Output
Uploaded Final
First, check if you have the GD extension installed, next,
Use the GD functions
//Loading the file
$rImg = ImageCreateFromJPEG("MyPicture.jpg");
//Font Color (black in this case)
$color = imagecolorallocate($rImg, 0, 0, 0);
//x-coordinate of the upper left corner.
$xPos = 100;
//y-coordinate of the upper left corner.
$yPos = 30;
//Writting the picture
imagestring($rImg,5,$xPos,$yPos,"My text in the picture",$color);
//The new file with the text
header('Content-type: image/jpeg');
imagejpeg($rImg, NULL, 100);
you can use this tutorial
http://blog.doh.ms/2008/02/12/adding-text-to-images-in-real-time-with-php/

Categories