Adding text on images - php

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);
}
?>

Related

How to store and get image from a image variable (SESSION)?

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.

Uploading a dynamic created image in php

To Achieve : Resizing uploaded image and save to the filesystem
-- Suppose a 1600x1024 image is being uploaded, and the required dimension is 500x300. Thus, the solution I came to is resizing image while uploading. The code snippet is as follows :
<?php
if(isset($_FILES['image'])){
//print_r($_FILES); die;
$file = $_FILES['image'];
//print_r($file); die;
$filename = rand().time().'.'.end(explode('.', $file['name']));
//echo $filename; die;
if(move_uploaded_file('"image.php?filename='.$file['tmp_name'].'"', 'uploads/'.$filename)){
echo 'Uploaded '.$filename.' !';
}else{
echo 'Not Uploaded';
}
}
?>
<form method="POST" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="file" name="image">
<input type="submit" value="Upload"/>
</form>
image.php
<?php
// Filename
$filename = $_GET['filename'];
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 500;
$new_height = 200;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Content type
header('Content-Type: image/jpeg');
// Output
imagejpeg($image_p, null, 100);
?>
Question is : How to use move_uploaded_files in the php created image with header Content-Type: image/jpeg
Thanks & Regards
You need to save the image using one of the following functions: imagejpeg, imagepng, imagegif, etc. If you set the second parameter to null, the raw image stream will be outputted directly. You need to specify image path there.
imagejpeg($image_p, 'new-image.jpg', 100);
If you want to detect image type automatically, you can use pathinfo to extract it.
Change from
if(move_uploaded_file('"image.php?filename='.$file['tmp_name'].'"', 'uploads/'.$filename)){
echo 'Uploaded '.$filename.' !';
}else{
echo 'Not Uploaded';
}
To
$resized_file = "image.php?filename=".$file['tmp_name'];
$resized_file = file_get_contents($resized_file);
if(file_put_contents('uploads/'.$filename, $resized_file))
{
echo 'Uploaded '.$filename.' !';
}
else
{
echo 'Not Uploaded';
}
You can use on same function or another file which you already use image.php.
I add some code on same function , is working for me please check for you.
if(isset($_FILES['image']))
{
//print_r($_FILES); die;
$file = $_FILES['image'];
//print_r($file); die;
$filename = rand().time().'.'.end(explode('.', $file['name']));
//echo $filename; die;
if(move_uploaded_file('"image.php?filename='.$file['tmp_name'].'"', 'uploads/'.$filename)){
echo 'Uploaded '.$filename.' !';
//once your file is uploaded you converting on same image
$filenameNew = $_GET['filename'];
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 500;
$new_height = 200;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Content type
header('Content-Type: image/jpeg');
//store path
$imageName=rand().time()."test.jpg";
$imagestore="uploads/".$imageName;
// Output
imagejpeg($image_p,$imagestore,100);
}else{
echo 'Not Uploaded';
}
}

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

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/

php content-type image size

I have this code to display users avatars..
<?php
include("../core/config.php");
if(isset($_GET['uid'])){
if(is_numeric($_GET['uid'])){
$uid = $_GET['uid'];
}
else{
exit();
}
$sql="SELECT avatar FROM users_avatar WHERE user_id = '$uid'";
$row= getRow($sql);
if(!$row){
$url = "../usravatars/_default/usravatar_default_m.png";
}
else{
$avatar = $row['avatar'];
$url = "../usravatars/$uid/$avatar";
}
header("Content-Type: image/jpg");
readfile($url);
}
?>
Is possible to set a custom size for the image being displayed?
Following is a sample function to resize the image on the fly. You can use your own specific width/height or fetch from the get variables.
function CroppedThumbnail($imgSrc,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.
//getting the image dimensions
list($width_orig, $height_orig) = getimagesize($imgSrc);
$myImage = imagecreatefromjpeg($imgSrc);
$ratio_orig = $width_orig/$height_orig;
if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
} else {
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width/2; //horizontal middle
$y_mid = $new_height/2; //vertical middle
$process = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
imagedestroy($process);
imagedestroy($myImage);
return $thumb;
}
//Create the thumbnail
$newThumb = CroppedThumbnail("DSC01088.jpg",$_GET['width'],$_GET['height']);
// And display the image...
header('Content-type: image/jpeg');
imagejpeg($newThumb);
With header("Content-Type: image/jpg"); readfile($url); you are sending the full image with its original size to the browser and nothing else.
If you want to display a resized version of the same image try something like
echo '<img src="' . $url . '" width="desired-width" />';
If you want to resize the original image then look at the first example on this page http://php.net/manual/en/function.imagecopyresampled.php

Categories