What's the problem with my php generated png file? - php

I want to make a unique forum signature from my latest watched animes in PHP. These are contained in an RSS feed. On my local apache server, the image is generated well, but as I upload it onto a server, I get an error, the picture isn't generated at all.
Here is my code and I wonder what's the problem since neither Dreamweaver CS5 or phpDesigner 7 don't show any errors, although if I press the Run button in phpDesigner, I get an error, but I don't know what it means. The error is the following:
Line: 6 - Fatal error: Call to undefined function imagecreatefrompng() in [php's path here]
So the code is the following:
<?php
// title & description arrays
$titleCuts = array();
$descCuts = array();
// bg image
$bgimg = imagecreatefrompng('sig_robin.png');
// colors
$white = imagecolorallocate($bgimg, 255, 255, 255);
$textColor = imagecolorallocate($bgimg, 245, 193, 9);
$shapeColor = imagecolorallocate($bgimg, 27, 20, 0);
// sxe <- xml url
$sxe = new SimpleXMLElement('http://myanimelist.net/rss.php?type=rw&u=fema', NULL, TRUE);
// shape
imagefilledrectangle($bgimg, 255, 20, 567, 279, $shapeColor);
// TEXTS
imagettftext($bgimg, 20, 0, 263, 52, $white, "my.ttf", "Latest Watched:");
// episodes' text
for($i=0;$i<5;$i++)
{
// title cut and joint
$titleCuts = explode(' ', $sxe->channel->item[$i]->title, -2);
$titleCut = implode(' ',$titleCuts);
// description (ep) cut and joint
$descCuts = explode(' ', $sxe->channel->item[$i]->description);
// output
imagettftext($bgimg, 10, 0, 270, 77+($i*45), $textColor, "my.ttf", $titleCut);
imagettftext($bgimg, 10, 0, 270+(strlen($titleCut)*7.2), 92+($i*45), $textColor, "my.ttf", "ep. ".$descCuts[2]);
}
header('Content-type: image/png');
// generating image
imagepng($bgimg);
?>
Thanks in advance.
Edit:
As I removed the header, now I get a lot of error that it can't find the font file, but I'm dead sure that I wrote it correctly.
They look like this:
Warning: imagettftext() [function.imagettftext]: Could not find/open font in ... on line 19

This means that GD either wasn't compiled into PHP or hasn't been loaded. First, check your php.ini, the path for which you can find with phpinfo() for extension=php_gd2.dll and make sure it's not commented out with a semicolon. After changing the setting, restart the webserver, then look at phpinfo() again to see if GD is loaded.

IF imagecreatefrompng is not defined, most likely the GD library is not installed, or broken, see: http://php.net/manual/en/image.installation.php
Don't be alarmed by the 'you have to configure and rebuild PHP', normally the package manager of your OS can easily add GD support by installing an extra package.

Ok, the solution for the second problem is that its a php bug http://bugs.php.net/bug.php?id=41336
But its easy to solve, in following way:
Put a ./ before every *.ttf file like in following example:
imagettftext(IMAGE, 0, 0, 0, 0, TEXT_COLOR, "./ttf_file.ttf", TEXT);

To use this function (imagecreatefrompng) your php needs to be installed with the GD extensions (for more information see this page.
To check what is / isn't install create a php file on your local server with just:
And then compare the image (GD) sections to the same file running on your server.
Note that if you are on a shared hosting server you'll probably have to contact their admins to install / configure this for you.

Related

Laravel 9: imagettftext(): Invalid font filename

I have a Controller method like this:
public function singleChar($text)
{
$font = 'SansBold.ttf';
...
imagettftext($img, $size, $angle + 5, $textX + 5, $textY + 10, $shadowgbColor, $font, $text);
...
}
But I'm afraid that's not right because I get this error:
imagettftext(): Invalid font filename
And I think this error occurs because I have wrongly called the font SansBold.ttf. So I wonder what the correct way of calling this font inside this Controller Method is? And also, where should I place the font?
Note that I'm using PHP v8 and also enabled GD Library by uncommenting ;extension=gd inside php.ini. I'm stuck with this and would appreciate any idea or suggestion.
you need to specify the full path to the font file.
it is better to use the public folder to store the font (if you need to have public access to it)
or the storage/app folder (if you only use it inside your laravel application)
In the first case, getting the path will look like this:
$font = public_path('fonts/SansBold.ttf'); // your file here: public/fonts/SansBold.ttf
In the second case:
$font = storage_path('app/fonts/SansBold.ttf'); // your file here: storage/app/fonts/SansBold.ttf

PHP how to output dynamic image

I think this will be an easy answer but I just can't figure it out.
I have a script that generates a pdf using fpdf and fpdi.
If I use a normal image then the pdf generates perfectly but I am trying to use an image generated dynamically by php.
$bc = new PrintBarcode('DARP CODE');
$bc->drawVoucher();
$src = $bc->getVoucher();
// image
$src = $bc->getVoucher();
$pdf->Image($src, 22, 94, 100, 15);
This gives the error:
FPDF error: Image file has no extension and no type was specified: Resource id #16
If I do
$barcode = imagejpeg($src);
$pdf->Image($barcode, 22, 94, 100, 15);
presumably because the imagejpeg is actually outputting the image but the image header is set because if the jpeg header is set the image will display fine so I'm just trying to figure out the correct way of doing this.
If it's easier, I have a separate script which can generate the image, e.g. `printbarcode.php' but I don't know how to get the contents of that script into this function:
$pdf->Image($barcode, 22, 94, 100, 15);
From the error message I would guess that the $pdf->Image() function is expecting $src to be a path to a file. What you are passing seems like a object.
Try saving the image to disk and loading from there. You are almost there with imagejpeg() function - see docs on php.net. Supply a path to save the file
imagejpeg($img, 'myfile.jpg', 90); // 90 denotes high quality
$pdf->Image('myfile.jpg', 22, 94, 100, 15);
...
unlink('myfile.jpg'); // delete after
or alternatively look for a function on the fpdf library that takes image resource as a parameter.
You don't need the image handler PHP uses to manipulate the image. What you need is the actual result of the image manipulation, namely the resulting file. Use imagejpeg($img, '/path/to/some/tmp/dir/file.jpg'); and hand the path over to your $pdf->Image() call. Then after creating the PDF you can safely remove the temporarily stored image, I think.
you have to do like this with the help of php's GD library..
//Create a new image from file or URL
$img_src = imagecreatefromjpeg($src);
// Output the image
imagejpeg($img_src);
// Free up memory
imagedestroy($img_src);

Image can not be displayed because it contains error in php gd

This is the Link I am following to create an image, however my GD is installed and working correctly as i tested with the very first example but this code breaks and flag "Image can not be displayed because it contains error" .
CODE -
<?php
//phpinfo();
//Report any errors
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Set the content type
header('content-type: image/png');
//Create our basic image stream 300x300 pixels
$image = imagecreate(300, 300);
//$image = imagecreatetruecolor(300, 300);
//Set up some colors, use a dark gray as the background color
$dark_grey = imagecolorallocate($image, 102, 102, 102);
$white = imagecolorallocate($image, 255, 255, 255);
//Set the path to our true type font
//$font_path = 'advent_light';
//$font_path = 'advent_light.ttf';
//$font_path = 'arial';
$font_path = 'arial.ttf';
//Set our text string
$string = 'Swapnesh!';
//Write our text to the existing image.
imagettftext($image, 50, 0, 10, 160, $white, $font_path, $string);
//Create our final image
imagepng($image);
//Clear up memory
imagedestroy($image);
?>
Things I tried and googled but with no solution are as follows - :(
Checked white/blank spaces before php tag if any.
Remove all code and spaces before header() method.
Changed imagecreate() to imagecreatetruecolor() as in comments in the code.
Checked font_path and set font path as per comments as well.
Followed this & this.
My PHP version - PHP Version 5.3.8
Still unable to locate the problem :(
Error
EDITS-
version 1.0
this is what im getting on saving.
More Info about image --
on saving the page -- this is the name of file saving -- create_png.php.png
version 1.1
<br />
<b>Warning</b>: imagettftext() [<a href='function.imagettftext'>function.imagettftext</a>]: Invalid font filename in <b>C:\xampp\htdocs\Core\CoreFiles\create_png.php</b> on line <b>20</b><br />
<br />
<b>Warning</b>: imagettftext() [<a href='function.imagettftext'>function.imagettftext</a>]: Invalid font filename in <b>C:\xampp\htdocs\Core\CoreFiles\create_png.php</b> on line <b>23</b><br />
Thanks to #cryptic and #user1711126
Solution --
Font file actually missing, we need to put our .ttf file under the folder to make this code working or set path to make it work.
Save the image file that errors and open it in a text editor like notepad or equivalent and see if any PHP errors are inside it. An error is occurring and outputting text then which corrupts the file. Do that and you will find what the error is.
I think #cryptic is right you need to use the real path for font use something like
$font_path = basename(dirname(__FILE__)).'/arial.ttf';
and please make sure the font exists in the directory.
I seriously doubted your font path, please double check your font and file in same directory and if it is, then change path like this,
$font_path = './arial.ttf';
Edit (As per Discussion in chat)
you must need an ttf file to use imagettftext() function place the arial.ttf file in your folder where your file reside

php include generated png in pdf via fpdf

I am trying to generate a PDF with an image that is also generated by php.
Sounds simple enough and I am sure I'm just screwing up the header but I can't seem to find a solution here.
first I generate a PDF:
define('FPDF_FONTPATH','fonts/');
require('scpt/fpdf.php');
class PDF extends FPDF {}
$pdf = new FPDF('P','in',array(8.5,11));
$pdf->SetAutoPageBreak(false,0);
$pdf->SetTextColor(0,0,0);
$pdf->SetDrawColor(0,0,0);
$pdf->SetFont('Helvetica','',12);
$pdf->Image('label.php?imgid=17',0,0,0,0,'PNG');
$pdf->Output('label.pdf','D');
then I generate the PNG in label.php:
if(isset($_GET["imgid"])) {
header("Content-Type: image/png");
$im = #imagecreate(110, 20)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
}
This will output: FPDF error: Not a PNG file:....
calling label.php?imgid=17 in the browser however will show me the image just fine...
What am I missing?
EDIT
In document:
Example
// Insert a logo in the top-left corner at 300 dpi
$pdf->Image('logo.png',10,10,-300);
// Insert a dynamic image from a URL
$pdf->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World',60,30,90,0,'PNG');
so it SHOULD be possible to include a dynamically generated image without saving it first?!
EDIT #2
I made it work with the library mem_image but the problem remains that this should not throw an error IMO?! So I leave this question open to see if there is indeed something wrong with my script of this turning out to be a bug.
You almost had it, you're missing only a couple things. First you need the full server address in the URL for your Image() call, so instead of
$pdf->Image('label.php?imgid=17',0,0,0,0,'PNG');
You need:
$pdf->Image('http://www.yourserver.com/label.php?imgid=17',0,0,0,0,'PNG');
That will eliminate the FPDF error you were encountering. Then to get FPDF to render your output correctly, you need to add a call to AddPage(), so your PDF generation script would become:
require('scpt/fpdf.php');
$pdf = new FPDF('P','in',array(8.5,11));
$pdf->AddPage();
$pdf->Image('http://www.yourserver.com/label.php?imgid=17',0,0,0,0,'PNG');
$pdf->Output('label.pdf','D');
Of course you don't need the SetTextColor(), SetFont(), etc if you're only including the single image. You didn't need the custom class definition either (I removed the unneeded lines).
Don't forget to substitute www.yourserver.com for the appropriate domain and path for your script.
The argument to the Image function needs to be a file, not a URL or another script. Since you already have your label script, the easiest work around would be to download the image to a temp location and then call $pdf->Image() with that temporary file.
This problem occurred With your file name,Make sure your passing file name is valid
function _parsepngstream($f, $file)
{
// Check signature
if($this->_readstream($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10))
$this->Error('Not a PNG file: '.$file);
...
}
View allow_url_fopen directive
http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
You need to do only changes that
require('fpdf.php');
and do the
$pdf->Image('http://www.yourserver.com/label.php?imgid=17',0,0,0,0,'PNG');
and run your code...
First, try to check your url with this code
$handle = fopen("http://www.yourserver.com/label.php?imgid=17", "rb");
print_r(fread($handle, 8192));
you with see what the contain in your url
**) make sure your url is not redirect to the login page
much more easy, only put .png in the final of dinamic chain and its all
example:
$pdf->Image('http://www.yourserver.com/label.php? imgid=17.png',0,0,0,0,'PNG');
or
$pdf->Image('../label.php?imgid=17.png',0,0,0,0,'PNG');
the mime type is not recognized in the url why does not appear png, if it's a stupid mistake but it is proven, google does the same by adding the extension with the url & PNG

Save HTML table as an image

I have a website I am building that takes data (the person's name) from a form and posts it into a customized "note" in a table on the next page. I want the user to then be able to save their "note" as an image with their customized name on it. Is there a way to save a SPECIFIC HTML TABLE as a PNG? Maybe take a screenshot of a specific coordinate on a web page?
If not is there a way to render posted PHP content from the form in an HTML canvas?
Any help would be great. I'm in a little over my head right now.
While you can render HTML using a variety of tools, you can't be sure that those tools will render the HTML the same way your browser renders it.
If your end goal is to generate an image with text on it, then let's solve that problem instead of trying to make the solution you suggested work.
Have a look at PHP's imagettftext() function. It contains an Example #1 which creates a small, simple image from text that can be stored in any variable ... including a form variable.
By using this example, and adding a few other of PHP's GD functions, you can make a decent replica of a table, and make sure it looks exactly the way you want it, rather than the way html2ps or some other tool renders it.
<?php
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = isset($_POST['name']) ? $_POST['name'] : "name";
// Replace path by your own font path
$font = 'arial.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
Here's sample output generated by the above script:
Note that you'll need to provide arial.ttf per the instructions at the link above.
If things don't work, look for errors both on-screen and in your web server's error log FIRST, before following up here. It's possible that PHP's GD module is not installed on your web server. If this is the case, you should check with your server administrator to make sure what you need is available to you.
You can try this JS library on client side.
workable solution
use fpdf to create pdf from html (table)
use imagemagick to convert pdf to png
You can also use Xvfb. It's a linux package. It stands for "X-window Virtual Frame Buffer" (if you were wondering why on earth it had such an esoteric name).
What that will do, is load a page, execute any JavaScript and apply the different stylings from CSS, all in the frame-buffer of the server. Then you can save the image.
Xvfb will probably not be available on most shared-hosting services, however, if that doesn't matter, then it would be a viable solution.
You can use something like html2ps

Categories