text to picture with mysql information - php

im building a website indianskincare.co.in which is coming out to what i want. the problem is i want to turn all text for each product into pictures as my client wants the text not to be so easily copied. i see how this is done using PHP by calling the PHP in the image source and the relevant code in the php.
it works on normal text wonderfully but when i include mysql row or any complex code it shows a broken image.
this works displays time and text
Header( "Content-type: image/png");
$image = imagecreate(320,130);
$date = date ("F dS Y h:i a");
$ip = "ip";
$fullip = "Your IP address is $ip.";
$black = ImageColorAllocate($image,0,0,0);
$red = ImageColorAllocate($image,204,0,0);
$white = ImageColorAllocate($image,255,255,255);
ImageFilledRectangle($image,0,0,320,130,$white);
ImageString($image, 14, 0, 0, "$fullip", $red);
ImageString($image, 12, 0, 24, "Time is $date", $black);
ImagePNG($image);
ImageDestroy($image);
I tried to add my mysql code between one of the variables (i didn't think it would matter between which) which works perfectly otherwise on another page but can't seem to change the text into picture.
mysql code
if(isset($_GET['id']))
{
$id=$_GET['id'];
$qry=mysql_query("SELECT * FROM Product WHERE id='$id'", $con);
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
/* Fetching data from the field "title" */
while($row=mysql_fetch_array($qry))
{
echo "<div style='overflow-x:hidden;width:20%;margin:0.5em;text-align:center;float:left;'>";
echo "<h3>".$row['name']."</h3>";
echo "<img style='width:100%;margin:0;' src='".$row['image']."' /><br>";
echo "<h1><img style='height:4%;' src='images/rs.png' />".$row['price']."</h1><br><a href='product.php?cat=".$row['short']."'>Back</a><br>";
echo "</div><div style='width:50%;float:left;'>";
echo "<h5 style='font-weight:normal;'>".$row['description']."</h5><br>";
so my question is how to modify the text from mysql array into image.
ps: i know mysql is being deprecated not preferred but ive already done the website using this and i will not be able to modify it to use the other methods

a time ago I use this class - and it works perfectly:
http://image.intervention.io/
Intervention Image requires the following components to work correctly.
PHP >= 5.3
Fileinfo Extension
And one of the following image libraries.
GD Library (>=2.0) … or …
Imagick PHP extension (>=6.5.7)
A good start is to install the composer:
https://packagist.org/
With the composer you can easily install PHP Packages / Modules for almost all issue.
Example from the page (how to convert text to an image)
// create Image from file
$img = Image::make('public/foo.jpg');
// write text
$img->text('The quick brown fox jumps over the lazy dog.');
// write text at position
$img->text('The quick brown fox jumps over the lazy dog.', 120, 100);
// use callback to define details
$img->text('foo', 0, 0, function($font) {
$font->file('foo/bar.ttf');
$font->size(24);
$font->color('#fdf6e3');
$font->align('center');
$font->valign('top');
$font->angle(45);
});
// draw transparent text
$img->text('foo', 0, 0, function($font) {
$font->color(array(255, 255, 255, 0.5))
});
So an example for your code could be (if intervention image class is working):
$result = array();
while($row=mysql_fetch_array($qry))
{
$result[] = array(
'name' => convertToImage($row['name'], $row['id'].'_name'),
'price' => convertToImage($row['price'], $row['id'].'_price')
)
}
function convertToImage($text, $name) {
$img = Image::make('images/transparent.png');
$img->text($text);
$img->save('images/'.$name.'.png');
return '<img src="images/'.$name.'.png">';
}
?>

Related

Echo does not show up a picture

Okay i have a site wich makes signatures. But because some header problems i had to put it in another file and use echo. this is the code:
<h1>Create your European Trucking signatures</h1>
<?php
echo '<img src="SigGen.php?player=$Playername&score=$Score&money=$Money" />';
?>
</div>
But it shows a broken image thingy. But when i go to the SigGen.php itself it does show up like here:
http://european-trucking.com/SigGen.php?player_name=Thimo
This is the code of SigGen:
<?
/*
***Made by: Nodroz***
*** Enjoy your signatures! ***
*/
$username="10528_Thimo"; //Your MySQL Username.
$password="*********"; // Your MySQL Pass.
$database="10528_Thimo"; // Your MySQL database.
$host="95.211.***.***"; // Your MySQL host. This is "localhost" or the IP specified by your hosting company.
$player_name=$_GET['player_name']; // This gets the player his name from the previous page.
/* Next, we will make a connection to the mysql.
If it can't connect, it'll print on the screen: Unable to select database. Be sure the databasename exists and online is. */
mysql_connect($host,$username,$password); // Connection to the database.
#mysql_select_db($database) or die( "Unable to select database. Be sure the databasename exists and online is."); //Selection of the database. If it can't read the database, it'll give an error.
/* To protect MySQL injection. */
$player_name = stripslashes($player_name);
$player_name = mysql_real_escape_string($player_name);
$query="SELECT * FROM Users WHERE Name='$player_name'"; // Gets all the information about the player.
$result=mysql_query($query);
$i=mysql_num_rows($result); // Here we are counting how many rows this result gives us.
/* We will now put the player's information into variables so we can use them more easily. */
/* DON'T FORGET: The names should be exact the same as in your mysql db.*/
if ($i == 1) // If the user has been correct, then it'll give us 1 row. If its 1 row, then it'll proceed with the code.
{
$Playername=mysql_result($result,0,"Name"); // Gets the username of the player and put it in the variable $Playername.
$Money=mysql_result($result,0,"Money"); // Gets the money of the player and put it in the variable $Money.
$Score=mysql_result($result,0,"Score"); // Gets the score of the player and put it in the variable $Score.
// Creating of the .png image.
header('Content-Type: image/png;'); // Don't touch this. We use this to tell the script we're working with an image.
$im = #imagecreatefrompng('PlayerSig.png') or die("Cannot select the correct image. Please contact the webmaster."); // Don't forget to put your picture there. Eg: playersig.png
$text_color = imagecolorallocate($im, 000,000,000); // RED, GREEN, BLUE --> Go to www.colorpicker.com, select a nice color, copy the R/G/B letters provided by colorpicker and put them here.
$text_username = "$Playername"; // This gets the information: player name to be showed in the picture.
$text_score = "$Score"; // Same as above but with score.
$text_money = "$Money"; // Same as above but with money.
$font = 'myfont.ttf'; //Upload your custom font to the directory where this file is placed. Then change the name here.
/* USAGE OF THE imagettftext: First ($im) shouldn't be changed. (16) is the text-size. (0) is the angle of your text. Change it, and you'll see what's going on. (20) is de X-coordinate of the text.
(36) is the Y-coordinate of the text. */
imagettftext($im, 16, 0, 5, 20, $text_color, $font, $text_username); // Prints the username in the picture.
imagettftext($im, 16, 0, 5, 40, $text_color, $font, "Score:");
imagettftext($im, 16, 0, 72, 40, $text_color, $font, $text_score); // Prints the score in the picture.
imagettftext($im, 16, 0, 5, 60, $text_color, $font, "Money:");
imagettftext($im, 16, 0, 72, 60, $text_color, $font, $text_money); // Prints the money in the picture.
imagepng($im);
imagedestroy($im);
} else echo('Username is not in our database. Please try again.'); // If the username doesn't exist (so the row is 0) then it'll give en error.
mysql_close();
?>
Anyone knows why it doesnt show up as an image using echo?
i think the problem is that you cant use variable names in string like this :
THIS WONT WORK
echo 'Hi $userName';
THIS WILL WORK
echo "Hi $userName";
so your line :
echo '<img src="SigGen.php?player=$Playername&score=$Score&money=$Money" />';
needs to be changed to :
echo "<img src='SigGen.php?player=$Playername&score=$Score&money=$Money' />";
try this...
<?php echo '<img src="SigGen.php?player='.$Playername.'&score='.$Score.'&money='.$Money.'" />'; ?>
use the concatenation features of the echo to properly append the variables to the image link

PHP output html when creating an image

I am trying to make a generator to output user data from my gaming website and I've never really looked into the conversion to images in PHP, however I've managed to get the basics of it working now from other questions on this site and elsewhere, anyway I was wondering whether it is possible to make my PHP file that generates the image, parse HTML tags in its' output? Here is my script:
<?php
$username = $_GET['username'];
$guild = $_GET['guild'];
$create = "Username: " . $username . " Guild: " . $guild . "";
$im = imagecreate(300, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $create, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
In my $create variable, I wish to use HTML tags but they aren't parsed as html and it outputs the tags in plain text.
Sorry, but PHP can't parse HTML before rendering it on an image. However, it does include various functions to change fonts and apply filters to the text. See http://php.net/manual/en/ref.image.php.
Is there a specific reason you need the information to be output as an image? Why not simply output the information using HTML?
Your browser parses HTML, php does nothing with it. You'll have to use stuff like \n in your string.

Is it possible to increase scale of map but still can be hovered efficiently? [Using PHP GD]

I give you guys a brief detail about my project. I'm working on a web application which is
a warehouse management system. Basically, I'm using PHP GD to draw an image of a factory's layout plan which contain racks and pallets on each floor.
When you hover on a rack or a pallet, you will be able to see the detail of it.
Because using GD, to be able to draw each rack or pallet, it need a specific coordinate of x and y, and also the width and height of it. I use the tag to create area so it could do the hovering with jquery.
I was asked to make a scale image with a given ratio and I wasn't able to figure out how to do it. So I think you guys can help me out.
Really need help on this.
Here are some example of my code
while($row = mysql_fetch_array($RecordsetZone)){
$n = substr($row['name'], 4);
$font = 2;
$textColor = imagecolorallocate ($source,0,0,0);
if($row['zonetype']=="Rack"){
imagerectangle($source, $row['xcord'], $row['ycord'] , $row['width']+($row['xcord']), $row['height']+$row['ycord'], $black);
imagefilltoborder($source, ($row['xcord'])+1, $row['ycord']+1, $black , $limegreen);
imagestring ($source, $font, ($row['xcord'])+2, $row['ycord']+5, $n, $textColor);
}
elseif($row['zonetype']=="Pallet"){
imagerectangle($source, $row['xcord'], $row['ycord'] , $row['width']+($row['xcord']), $row['height']+$row['ycord'], $black);
imagefilltoborder($source, ($row['xcord'])+1, $row['ycord']+1, $black , $dodgerblue);
imagestring ($source, $font, ($row['xcord'])+5, $row['ycord']+2, $n, $textColor);
}
}
this is how I drew the image by getting the x, y from the database
<map name="testmap" id="testmap">
<?php $RecordsetZone = mysql_query($query, $cakewms) or die(mysql_error());
while($row = mysql_fetch_array($RecordsetZone)){?>
<area id=<?php echo '"'. $row['name']. '"';?> shape="rect" coords=<?php echo '"'. $row['xcord']. ','.$row['ycord'].
',' . ($row['width']+$row['xcord']) . ',' . ($row['height']+$row['ycord']) . '"';?> href="#" alt="Sun" />
<?php }?>
</map>
after that use map to create area for hovering
if I change the ratio, can I still hover on the right area?
You can use special JQuery plugin ImageMapster.
It allow resize image-maps, while they still stay with correct marked active zones.
So, you will need generate your image-map once, and recounting onresize will be the task of this plugin.
It can also be helpfull in other cases of working with imagemaps.

PHP header, Content type: image not allowing text

I have a variable ($output) that is set to a string.
To mekt this string an image I'm using the PHP: GD Library.
In particular the imagestring() function, which I'm using with a very slight modification:
<?php
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, $output, $textcolor); #here is my string $output
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
This is working as expected: It turns $output into an image.
So, my problem is (or my best guess at least):
header('Content-type: image/png');
Which, doesn't allow me to output any html after that.
So I read this question, which asks if you can use two headers, which you can't, but the accepted answer recommends, something like this: <img src="my_img.php" />
This of course would be fine, except I don't know how would this solve my issues since, since even if I knew the source to this image (which I don't - so, that would be my first question, what's the path to the generated image*) I't would change the fact that the header is there and is not letting me output text.
So, I how would you approach this issue?
Thanks in advance!!
*I guess that would solve my issues since I could do this on an external file, and the just call the image (but maybe not since I would have to do an include and this would include the header too) as you see I'm a bit confused. Sorry :)
UPDATE:
So I'm seeing my question was confusing so I will add some more code to see if this clarifies my problem a little bit more:
<?php
$x = mt_rand(1,5);
$y = mt_rand(1,5);
function add($x, $y) { return $x + $y; }
function subtract($x, $y) { return $x - $y; }
function multiply($x, $y) { return $x * $y; }
$operators = array(
'add',
'subtract',
'multiply'
);
$rdno = $operators[array_rand($operators)];
$result = call_user_func_array($rdno, array($x, $y));
session_start();
$_SESSION['res'] = $result;
if ($rdno == "add") {
$whato = "+";
}elseif ($rdno == "subtract") {
$whato = "-";
} else {
$whato = "*";
}
$output = $x . $whato . $y . " = ";
?>
<form name="input" action="check.php" method="post">
<input type="text" name="result" />
<input type="submit" value="Check" />
</form>
I want $output to be a image so this got me trying to use the PHP:GD script above, but I can't make put in the same file because of the header.
You need to make a separate PHP script which serves the image, then make an <img> tag that points to this script.
You can send information to the script using the querystring in the image URL.
Morbo says: "Windmills do not work that way! Goodnight!"
Which means that you need to bone up on how this all works. This issue points to you having a basic misunderstanding of your tools. HTML can't contain images, it contains links to images. So your script needs to be included from another page via an image tag. (or CSS)
However, all this is a good thing. It means that this script can have dynamic elements that produce a new image each time it is called. Or that it could password-protect your images so only logged-in users can see it.
There are a host of ways to use this. And once you realize the image is like a page to php, this opens new routes. Php can output anything. Word docs, excel, pdf, css, even JS. all of which can be used to do cool things.
Just think of the image as a separate page. You'll get it. It'll just click into place in your mind. One of those big 'aha' moments.
First, the path.
From the manual :
imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )
It means that if you don't give a second argument (it is the case here), you don't have the path to a file but the data of the file / image ressource. The php file will be understand as a png file by the browser thanks to the header you give.
Second :
In your page (ie index.php), you could add this like that
<img src="myimg.php?output=[...]" />
and in your php script myimg.php you have it like this :
<?php
$output = $_GET['output'] // getting your text
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, $output, $textcolor); #here is my string $output
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
2 separates files.
You can send the image inline with echo '<img src="data:image/png;base64,'. base64_encode(imagepng($im)) .'" /> instead of <img src="my_img.php">.
Do not set a content-type header! Your output is text/html what you don't have to announce as it's the default in most server setups.
HTTP doesn't work that way. When your are serving image/png data, it as if you are serving a png file from the site, not an html file with an image in it. What are you trying to accomplish?
my_img.php is not source to your image. It is a source to the script generating that image, or reading it from file and outputting directly into browser. Obviously the approach with img src would be the best, because you'll hide all "boring" implementation of displaying image string behind browser's mechanisms.

Dynamic GD image width text

I'm trying to spice up my website by using custom fonts for headings. For me, the most appropriate way to do this is using PHP and GD. I have written a little script which will output the dynamic text based on the $_GET value, however sometimes the image is too wide, which moves everything else about.
How can I get the image to adjust the width of it, based on the width of the text? Here is the code I've written so far:
<?php
// Settings
$sText = $_GET['t']; // Text of heading
$sFont = "font/AvantGarde-Book.ttf"; // Default font for headings
$sMain = $_GET['c'] ? $_GET['c'] : 0xF2AB27; // Get a font or default it
// Create the image
header("content-type: image/png"); // Set the content-type
$hImage = imagecreatetruecolor(200, 24);
ImageFill($hImage, 0, 0, IMG_COLOR_TRANSPARENT);
imagesavealpha($hImage, true);
imagealphablending($hImage, false);
imagettftext($hImage, 20, 0, 0, 24, $sMain, $sFont, $sText); // Draw the text
imagepng($hImage); // Generate the image
imagedestroy($hImage); // Destroy it from the cache ?>
Thanks!
Ok, I figured it out! For anyone else who may have this problem, you need to add:
// Calcuate the width of the image
$arSize = imagettfbbox(24, 0, $sFont, $sText);
$iWidth = abs($arSize[2] - $arSize[0]);
$iHeight = abs($arSize[7] - $arSize[1]);
Before the imagecreatetruecolor()
The function imagettfbbox will calculate the size of what the text will be based on the font you picked. Use the results in your call to imagecreatetruecolor.

Categories