I am a student taking a php course and I have been assigned to create a function that creates a square based on a given set of parameters and prints it, but I must use an include statement to print all of the squares.
My Function looks like this :
function squareFunction ($size, $r, $g, $b, $backR, $backG, $backB, $posX, $posY, $length, $height) {
//create an empty image background
$imgur = imagecreatetruecolor($size, $size) or die('Cannot initialize new GD image stream');
//define the foreground and background colour
$fgcolour = imagecolorallocate($imgur, $r, $g, $b);
$bgcolour = imagecolorallocate($imgur, $backR, $backG, $backB);
//fill the image with the background colour
imagefill($imgur, 0, 0, $bgcolour);
//draw the rectangle using coordinates defined by the functions paramters
imagefilledrectangle($imgur, $posX, $posY, ($posX + $length), ($posY - $height), $fgcolour);
//output the header to tell browser this is a png
header ('Content-type: image/png');
//Write the image to be a png out
imagepng($imgur);
imagedestroy($imgur);
}
and is inside of a file called square.php
However when I try to use include "square.php"; in a seperate php file for example:
<?php
include '../../../square.php';
echo squareFunction(400,0,0,0,100,100,100,0,50,50,50);
?>
I just get a broken image link.
I then tried to include a function call at the top of my square.php file, but then when I used the include statement it would just print the square as soon as the include was read and did no other statements in my file.
Sorry for the lengthy post but I have been researching this all week and could not find any information on why this was happening, thank you all in advance.
Related
is there a function that will convert hex colors to image and save it as png?
example :
$pixelrow1 ["000000","000000","000000"];
$pixelrow2 ["000000","FFFFFF","000000"];
$pixelrow3 ["FF0000","00FF00","0000FF"];
function convert_to_image($row1,$row2,$row3,$path_to_save) {
// Some function
}
convert_to_image($pixelrow1,$pixelrow2,$pixelrow3,"c:/image.png");
I really have no idea if is it possible or not, but i'm pretty sure that its possible because you can make image using php
The output should return like this :
You can do it like this, but hopefully your variables have more sensible names and you can use a loop:
<?php
$im = imagecreate(3,3);
$black = imagecolorallocate($im,0,0,0);
$white = imagecolorallocate($im,0xff,0xff,0xff);
$red = imagecolorallocate($im,0xff,0,0);
$green = imagecolorallocate($im,0,0xff,0);
$blue = imagecolorallocate($im,0,0,0xff);
# First row
imagesetpixel($im,0,0,$black);
imagesetpixel($im,1,0,$black);
imagesetpixel($im,2,0,$black);
# Second row
imagesetpixel($im,0,0,$black);
imagesetpixel($im,1,1,$white);
imagesetpixel($im,2,1,$black);
# Third row
imagesetpixel($im,0,2,$red);
imagesetpixel($im,1,2,$green);
imagesetpixel($im,2,2,$blue);
imagepng($im,"result.png");
?>
The real problem is not saving the data into the file you want.
The real problem is saving the data IN png format.
You should read how png saves the data.
Or you can play a little with PHP image resources.
Maybe this snippet of code can give you some advice:
<?php
header("Content-Type: image/png");
$im = #imagecreate(1, 1);
// Creates a 1x1 image resource
$background_color = imagecolorallocate($im, 0xFF, 0x00, 0x00);
// Adds a red background color to the only pixel in the image.
imagepng($im);
// Sends the image to the browser.
imagedestroy($im);
?>
If you wanna take a look at all the functions for the images:
http://php.net/manual/en/ref.image.php
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.
I'v searched all day for a function to resize my pictures on the server on the fly, without saving them.The code works, it shows the full size images, now I want to make them smaller.
This is the function:
function resize_image($file, $width, $height) {
if (file_exists($file)){
$image = imagecreatefromjpeg($file);
list($orig_width, $orig_height) = getimagesize($file);
$ratio = $orig_width / $orig_height;
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}
$new_image = imagecreatetruecolor($width, $height);
imagecopyresized($new_image, $image,
0, 0, 0, 0,
$width, $height,
$orig_width, $orig_height);
// header('Content-type: image/jpeg');
imagejpeg($new_image, NULL, 80);
}
}
From what I searched today I need to put the header (Content-type: image/jpeg') for the browser to recognize the output as an image but if I do that it stops the script.
This is the page using it:
<? include('resize.php');
$chapter='test';
$query=$db->prepare("SELECT * FROM `test_db` WHERE `test_db`.`Chapter` LIKE :? ORDER BY `id` ASC LIMIT 0, 6");
$query->bindValue(1, $chapter, PDO::PARAM_STR);
$query->execute();
$rows= $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row){
echo "<li><h2>".$row['Name']."</h2></li>" ;
resize_image("_images/".$row['img_number'].".jpg", 300, 190);
};
?>
You cannot output html and images to the browser in the same script.
You should either:
use a separate script to output the image and call that from the html like (simple example):
<img src="your_script.php?id=XX&size_x=XX&size_y=XX">
save the images to a file and link to that file from your html.
You could also encode the images as base64 strings and use that in your image tags but that would lead to a very large html file unless you are talking about simple buttons.
Don't put your closing tag in PHP. It will output whitespace after the closing tag which will alter the result.
Since when are headers stopping the script?
And yes, the reason why resized files are saved, is (1) you'll probably need them again, (2) the content type makes them an image in stead of text. If you want to resize those 'inline' you'll need two content types, and I guess that won't work that well...
What you could do, is resize and save the file, serve it and delete it. Like a temporary image file. A more direct way doesn't exist, according to me. But if I'm wrong, please point that out in the comments for me. I like to learn new stuff ;)
Edit: okay, EXCEPT when the script only handles the image resizing. Just thinking about that one right now. Sorry :)
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.
I have a 1 pixel tall by 760 pixel wide image that I use as a repeating vertical background image. The right side of this image is filled with a spot color (the remaining left side of the image is white).
The purpose of this background image, in my css based layout, is that it provides the illusion that the sidebar background color runs all the way down the page (easy to do with tables, but no so much with CSS positioning).
What I need to do is to figure a way to feed a php script (background-image.php) which contains the imagecreatefromgif function, a hex number and have it use that to repaint the spot color of the image to match the spot color that's passed in and save the resulting image onto the server, overwriting the default one.
Ideally, I'd not like to have to call this function everytime the template loads, and onlydo it when the user elects to change the template colors. So once they do that, I'd just like to modify the existing image I've got on the server which will always be called "sidebar_bg.gif"
Any ideas on how to do this are much appreciated.
Something like this could do it:
$token = md5(serialize(array($red, $green, $blue)));
if (!file_exists('cachedir/'.$token.'.gif'))
{
$img = imagecreatefromgif('origfilename.gif');
$color = imagecolorallocate($img, $red, $green, $blue);
for ($i = $startPixel-1; $i < $endPixel; $i++)
{
imagesetpixel($img, $i, 0, $color);
}
imagegif($img, 'cachedir/'.$token.'.gif');
}
serveFile($token);
EDIT: Added caching to example code
Just an addition to this post. You can convert HEX color into RGB notation with the folowing function:
function hexToRGB ($hexColor)
{
$output = array();
$output['red'] = hexdec($hexColor[0].$hexColor[1]);
$output['green'] = hexdec($hexColor[2].$hexColor[3]);
$output['blue'] = hexdec($hexColor[4].$hexColor[5]);
return $output;
}
e.g. try:
var_dump(hexToRGB("FFFFFF"));