Why is php code not giving the output of image? - php

this is the code
<?php
$x = imagecreatetruecolor(250, 250);
$y = imagecolorallocate($x, 120 ,156,100);
header('Content-Type: image/jpeg');
imagejpeg($x);
?>
It is giving output as
The image "http://localhost/firstprogram.php" cannot be displayed because it contains errors.
I also tried Example from https://www.php.net/manual/en/function.imagerectangle.php and it still displayed the same message.
And also can someone tell if header is necessary or not and what exactly is it used for?

you made a image, you allocate it, but you did not draw it.
try this code
<?php
$x = imagecreatetruecolor(250, 250);
$y = imagecolorallocate($x, 120 ,156,100);
imagerectangle($x, 50, 50, 150, 150, $y);// draw the rectange of image
header('Content-Type: image/jpeg');
imagejpeg($x);
?>

Related

imagejpeg shows a blank image for creating captcha

I tried 3 different codes to create a captcha for my php project,but they all showed gibberish html instead of actually executing it.
I tried both imagepng and imagejpeg and even added the header attribute,but instead of working,it shows nothing but a blank image in the middle of the browser page.I looked up all stack overflow questions for this,but none seems to work for me.
When I remove the header attribute it writes gibberish but when I remove it it shows me a blank image.Is there anyone that can help me?
Here's the last code I coded:
<?php
session_Start();
$length = rand(0,56);
$shuffle=str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
$text = substr($shuffle,$length,6);
$_SESSION["captcha"] = $text;
$im = imagecreatetruecolor(18,22);
imagecolorallocate($im,255,255,255);
$fontSize = 24;
$rotate = 13;
$xRotate = 50;
$yRotate = 70;
$font = getcwd()."\\public\\fonts\\arial.ttf";
$color = imagecolorallocate($im,255,0,255);
imagettftext($im,$fontSize,$rotate,$xRotate,$yRotate,$color,$font,$text);
header('Content-Type: image/jpeg');
imagejpeg($im);
?>

PHP failure: imagejpeg and imagecreatefromjpeg

I check StackOverflow to see if this question has been answered, but didn't find anything corresponding to this.
Running Wampserver 3/Apache 2.4.18/PHP 7.0.4/MySQL 5.7.11. This simple example that I copied from StackOverflow doesn't work -- no image is displayed. Extension php_gd2 is enabled (get_extension_funcs("gd") shows the list).
I had to comment out the header(); code (even if I put it at line 2), because Firefox complained the code is incorrect with it.
<?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);
// Set the content type header - in this case image/jpeg
//header('Content-Type: image/jpeg');
// Output the image
imagejpeg($im);
// Free up memory
imagedestroy($im);
?>
If I try to load in image from a file:
<?php
$thumb = imagecreatefromjpeg("http://localhost/newthumb.jpg");
if( imagejpeg($thumb)){
imagedestroy($thumb);
echo "<br>Image2 created";
}
else {
echo "<br>Image2 not created";
}
?>
I get what is tantamount to a character dump of the file (the # are black diamonds with ? in them):
####JFIF##>CREATOR: gd-jpeg v1.0 ...
Image2 created
What the !##$! happened with the new Wampserver/Apache/PHP/MySQL??? What does it take to get images to display in PHP?

PHP function not displaying barcode using TrueType fonts

Hello I am using a function that I found in Internet to display a barCode using a TrueType font, here is the code:
//For displaying barcodes
//Arguments are:
// code Number you want outputted as a barcode
//You can use this script in two ways:
// From a webpage/PHP script <img src='/images/barcode.php?code=12345'/>
// Directly in your web browser http://www.example.com/images/barcode.php?code=12345
//Outputs the code as a barcode, surrounded by an asterisk (as per standard)
//Will only output numbers, text will appear as gaps
//Image width is dynamic, depending on how much data there is
header("Content-type: image/png");
$file = "barcode.png"; // path to base png image
$im = imagecreatefrompng($file); // open the blank image
$string = "123123123"; // get the code from URL
imagealphablending($im, true); // set alpha blending on
imagesavealpha($im, true); // save alphablending setting (important)
$black = imagecolorallocate($im, 0, 0, 0); // colour of barcode
$font_height=40; // barcode font size. anything smaller and it will appear jumbled and will not be able to be read by scanners
$newwidth=((strlen($string)*20)+41); // allocate width of barcode. each character is 20px across, plus add in the asterisk's
$thumb = imagecreatetruecolor($newwidth, 40); // generate a new image with correct dimensions
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, 40, 10, 10); // copy image to thumb
imagettftext($thumb, $font_height, 0, 1, 40, $black, 'B2FI25HRc.ttf', '*'.$string.'*'); // add text to image
//show the image
imagepng($thumb);
imagedestroy($thumb);
I cannot find the error why the function doesn't display the image. Any ideas? The font is in the same directory with the php function and I tried relative and absolute paths to the font with no results. Any suggestion?
Thank you very much
You need to check for error messages.
For debugging, comment out the header line and add these lines on the top to show all errors:
ini_set('display_errors',true);
error_reporting(E_ALL);
In many cases the error messages will tell you pretty clear whats wrong.

Rotated image wont display in php

So i am trying to create a compass to show wind direction.
Function rotate($angle) {
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $angle, 0);
return $compass;
}
That will be displayed using some html that i am echoing. The variable angle is being passed from a database. The html on the php script looks like this:
<img src='".rotate($row['wind_dir'])."'/>
The image never displays, and clearly the browser does not know where it is.
When i view the html in my browser, the above line shows as
<img src="Resource id #4"/>
and when i click on it, it navigates to a 404.
What am i doing wrong? Have i forgotten a line in the image rotation function?
EDIT:
Having tried some of the responses below, i get an image, but it only shows as a black box!
EDIT2:
Well after much fiddling, it turns out all that was needed was to the third value of imagerotate() to -1 as follows:
$original = imagecreatefrompng("img/goog.png");
$compass = imagerotate($original, $angle, -1);
imagealphablending($compass, true);
imagesavealpha($compass, true);
header('Content-Type: image/png');
imagepng($compass);
imagedestroy($compass);
I posted a comment about using CSS or JS rotation instead but since then I've had a better idea.
The compass is always going to be Arrow.png in one of 360 positions.
Use a batch process in Photoshop or PHP to create 360 versions. One for each degree. Then you can just call Arrow_120.png for example for 120 degrees. You remove the issue with your existing code of creating images on the fly while avoiding compatibility issues with CSS / JS.
You have to execute the function and send header: try like below, say our php file name is rotate.php :
rotate.php
function rotate($angle) {
$original = imagecreatefrompng("test.png");
$compass = imagerotate($original, $angle, 0);
header('Content-Type: image/png');
imagepng($compass);
imagedestroy($compass);
}
if(isset($_GET['angle'])){
rotate($_GET['angle']);
}
THen in your html you can call the web resource i.e you php file as:
<img src="url_to_rotate.php?angle=90" />
Also remember to sanitize the GET input before executing it.
The displayed image should be a image file. To achieve this you should use imagejpeg();
So basically you should have 2 php files:
1: Creates the image file using your code and imagejpeg();
<?php
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $_GET['angle'], 0);
header('Content-Type: image/jpeg');
imagejpeg($compass);
?>
2: The php file that displays the image.
<img src='image.php?angle=".$row['wind_dir']."'/>
if you want just one file you could do the following:
<?php
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $_GET['angle'], 0);
ob_start();
imagepng($compass);
$stringdata = ob_get_contents();
ob_end_clean();
$imageData = base64_encode($stringdata);
$src = 'data: image/png;base64,'.$imageData;
echo '<img src="',$src,'">';
?>

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.

Categories