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,'">';
?>
Related
This question already has answers here:
php: recreate and display an image from binary data
(5 answers)
Closed 3 years ago.
I am trying to get Image from FTP server and print it afterwards without saving it locally. My problem is, that the image is in some kind of crypted form probably, or in Binary, honestly I have no idea.
This is a code I do have so far:
public function getImagePreview($imageName){
if(ftp_get($this->connection, "php://output", "web/media/images/".$imageName, FTP_BINARY)){
$data = ob_get_contents();
$dataSize = ob_get_length();
ob_end_clean();
return array('data' => $data, 'size' => $dataSize);
}else{
return false;
}
}
It's a method inside one object that I am calling from a file and here is a the code I am trying to show the image.
This line is for getting the Image (calling the function above), but it's a different PHP file! This is a view file.
require_once "../objects/ftpm.php";
$ftpM = new FTPManager();
$image = $ftpM->getImagePreview($imageName);
And here I am trying to print the image.
<span> Preview </span>
<img class="materialboxed" width="650" src="<?php echo $image["data"]; ?>"/>
But it actually shows tons of this code (I showed only a few lines as an example, since it's so extremely long):
����JFIFdd��Duckyd��Adobed������Ul��� u!"1A2# QBa$3Rq�b�%C���&4r ��5'�S6��DTsEF7Gc(UVW�����d�t��e�����)8f�u*9:HIJXYZghijvwxyz�������������������������������������������������������m!1"AQ2aqB�#�R�b3 �$��Cr��4%�ScD�&5T6Ed' s��Ft����UeuV7��������)��������������(GWf8v��������gw��������HXhx��������9IYiy��������:JZjz����������?��ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^���ߺ�Pq�uHRh����<��fV��(�u ���nG�u�Tb��?��1g�,�Q�9g��6GԼ����ӌ��X J��G���4�abk>�F�b1��ޖ��x%w>$y�{�M]^���UZ�Kma��{��^�><���VX�y����4���V�p?�GɆ��^3L�gO4_s5���B���7�[���u�|B���&a���l�nm��s��E-%�ԽEi�-<2��2�b5����-� {�^�=}3:�WQhjVL�[PY��Y�bC�JX����y����i*�Ӗ�2�t�GD�e Dͨ$r�K�r\X}8�^�W�� jI�"��,ji|0$S�U��J��.�R�H��}��t���-fBi�.6����$��b�+{\���~��a�����%:����Y�$���9U�}���Ҷ�YVq�Z�ɞ9�xPL嘆q�r��p-��{�,\k5��3�KG�!��Le�Ą�����b�/S 4�ߠ�#i�d�ԓoΛ{�^�g���>#�9$8��:CH�jF$��*)��u�Q�}��t#����F���2:0ee?B� ~��r����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^����u�~��{ߺ�^ c�>�Bg6.�ԤoGY&�ii�B��RD��f-� ?�}��t϶Z�-F��;kI�j����7��\�ԅmc�C��?B�K)"�a��a��u�r �h�r��,�,�_+k*�O��{�^���MU5\��4�G��+ Y�+1C�������{���t��]K�k�X��L�e(�uCq~��$1{*��_���_S�����䶩N���>���VIG�����L�J���Sn8���{��L��w�'��2��hb���2<�8b��rH7~m��{��^K�f�/�䤍i*8Y����#��ʗck)��>�a�9s9�Zq9ZX�Q���o!���j &�U��I��6ߺ�K��0�S�]T�jii֊/�>o=\�-eBO�_�{�=NRz$�t����5%|�J)�����J,����X�#�����{�/%OY����� rX(Q�b=��t��N�I;F�Lg���6�#��e]Ib����/��{��E�Ʀ#�1hI"G���44�T�A��������k�����(��\R�Z2Y������>�o��{�^�7SUG)ED2���&���F�l�^_�z�U��*j�)�h�����2����#��� e1�Z����=��t1�I�|5-VJ�9ni%�Ti$Q��X��UTF����~~��Y���WӭM$�OM��&���c��0������~��4U;N�^$E{8
Thank you for any help!
$ftpM = new FTPManager();
$image = $ftpM->getImagePreview($imageName);
$type = 'jpeg'; // file type here
header("content-type: image/{$type}");
echo $image['data'];
I have a database which includes a table of jpeg photo data. This data has been sent to the database from an iPad app and can be displayed in a webpage using the following:
$photo_query = "SELECT photoID, photoData FROM tblPhotos;";
$resultPhotos = mysqli_query($connect, $photo_query);
while($rowPhotos = mysqli_fetch_array($resultPhotos)) { ?>
<div id="photo"> <?php
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['photoData']) .'"/>';
</div>
}
This works fine and the image displays correctly.
I am now looking to add a simple tool to rotate this image. Below the image is a simple and when this is clicked the javascript function updatePhoto is called with the photoID:
<div onclick="updatePhoto('<?php echo $photoID; ?>')">Rotate</div>
JAVASCRIPT
function updatePhoto(photoID) {
$.post("photoChange.php", {
photoToChange: photoID
},
function(data, status){
document.getElementById('photo').innerHTML = "<img src='data:image/jpeg;base64, base64_encode(" + data + ")'/>";
});
}
PHOTOCHANGE.PHP
$photoID = $_POST['photoToChange');
$select_photo_query = "Select photoData From tblPhotos where photoID= '" . $photoID ."';";
$resultPhotos = mysqli_query($connect, $select_photo_query);
while($rowPhotos = mysqli_fetch_array($resultPhotos)) {
$source = $rowPhotos['photoData'];
}
$degrees=90;
$image = imagecreatefromstring ($source);
$rotate = imagerotate($image, $degrees, 0);
$finalImage = imagejpeg($rotate);
//step to convert jpeg back to binary needed?
echo $finalImage;
This all works in that the photoID is sent to photoChange.php, the source is retrieved from the database etc and data is sent back and placed into the page. But it does not display an image, just lots of data. I know I have a coding issue here but I am not sure exactly what.
I have tried removing all the rotation detail and simply echoing the $source unchanged and this does not replace the image with itself but with lines of data instead. So I wonder if there is an issue when posting data and echoing data back whether I need to stipulate a coding method being used?
Any assistance much appreciated.
Go to: http://php.net/imagejpeg
It returns a boolean value and directly dumps the image to the output.
$finalImage = imagejpeg($rotate);
//step to convert jpeg back to binary needed?
echo $finalImage;
Instead of this, add the content type and let the image render straight (you don't need echo, echo is implicit on imagejpeg()):
header('Content-Type: image/jpeg');
imagejpeg($rotate);
More problems:
You have <div id="photo"> in a while loop, which makes your ID not unique, it can't work when you have more than 1 picture
Another problem:
You interpolate PHP in Javascript a way it won't work ever. Replace the line by this with fixed concatenation:
.innerHTML = "<img src='data:image/jpeg;base64, " + data + "'/>";
Put the base64 encode in the image creation step, we make use of output buffer there:
header('Content-Type: text/plain');
ob_start();
imagejpeg($rotate);
$binary = ob_get_contents();
echo base64_encode($binary);
ob_end();
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.
I have a page with a bunch of animated gifs and I would like to use PHP to either freeze them on page load or convert each one to jpg/png. I came across this http://php.net/manual/en/function.imagecreatefromgif.php but I'm not too familiar with PHP. Any help?
Here is the code to convert animated gif to jpg. Taken from This comment on the PHP manual entry
<?php
//This function gif2jpeg take three parameter as argument. two argument are optional
//first will take the gif file name. second for file name to save the converted file. third argument is an color array
//EXAMPLE:
$gifName = $_GET['gif_name']; //ABSOLUTE PATH OF THE IMAGE (according to its location)
$c['red']=255;
$c['green']=0;
$c['blue']=0;
echo gif2jpeg($gifName, '', $c);
function gif2jpeg($p_fl, $p_new_fl='', $bgcolor=false){
list($wd, $ht, $tp, $at)=getimagesize($p_fl);
$img_src=imagecreatefromgif($p_fl);
$img_dst=imagecreatetruecolor($wd,$ht);
$clr['red']=255;
$clr['green']=255;
$clr['blue']=255;
if(is_array($bgcolor)) $clr=$bgcolor;
$kek=imagecolorallocate($img_dst,
$clr['red'],$clr['green'],$clr['blue']);
imagefill($img_dst,0,0,$kek);
imagecopyresampled($img_dst, $img_src, 0, 0,
0, 0, $wd, $ht, $wd, $ht);
$draw=true;
if(strlen($p_new_fl)>0){
if($hnd=fopen($p_new_fl,'w')){
$draw=false;
fclose($hnd);
}
}
if(true==$draw){
header("Content-type: image/jpeg");
imagejpeg($img_dst);
}else imagejpeg($img_dst, $p_new_fl);
imagedestroy($img_dst);
imagedestroy($img_src);
}
?>
How to use:
Add the above code into a php file 'convertGifToJpeg.php'
Add an <img tag. <img src="http://apllicationdomainpath/convertGifToJpeg.php?gif_name=/images/animated_gif.gif" width="200" height="200" />
Make sure have given correct name/path for both the gif image and php file.
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.