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'];
Related
This question already has answers here:
Output an Image in PHP
(12 answers)
Closed 4 years ago.
Well, my page contains an img like this:
<img id=".."class=".." src="setPhoto/second_photo.php">
Now, as you can see in src I have put a .php file:
<?php
$id = $_SESSION['u_id'];
$sql = "SELECT * FROM users WHERE id=$id";
$result = mysql_query("$sql");
if ($row = mysqli_fetch_assoc($result)) {
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['profile_front_photo'];
} else {
// no result from database
mysql_close($link);
header("Content-type: image/jpeg");
echo '../../../_images/default.jpg'; //Here is the promblem
}
?>
This code with the path, is not working. I want to set a photo to img by using a path.
Is it possible?
The browser asked for an image. Instead of getting an image back, it got back a string "../../../_images/default.jpg".
Instead, you want to open that file and pass its contents through. You also need to set the correct MIME type in the response.
You should be able to find simple tutorials for this online, or take a look at e.g. https://secure.php.net/manual/en/function.fpassthru.php
You can try this:
dirname(__FILE__)
it will get the root folder your project and then you specified your path like this
dirname(__FILE__). '/imagefoldername/_images/default.jpg';
Make it
$path='../../../_images/default.jpg';
echo "<img src='.$path.'>";
For my current assignment I'm trying to store files into the DB and display them. Currently I have no problem storing the files but I can't display them properly. I'm using this in my main form.
<td><a href=getImage.php?id='.$file[0].'" />Resume</a></td>
And this is the query I'm using to get the file out of the DB.
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo "<img src=\"{$row['file']}\" /><br />";
The result is
…³V!µÔ¢ošweöÿZ–îÌèEÈÎpEJ·˜kä€òþòâGas
È*G¨¥vA¤uEN¤S]‰:ñY“iwØ8‡¥e]ØÝGÑ‘øQÍ!«3¨ÄvÙÁu§]zÕÿOã^ssÌuáY7WP“ÔT6Æà™ëâþÊQË!üioe8
9ô5ã?ÛSÇÔ‘RÃ⛘VCBh¹>ϳ=BïÃVwåçÔW#¯|8†ufŠ4ob1PiÞ=q(,>µÐYx®Æ÷¥ò›Ñ5b½äy6«ðÆbͲϡ®fóá–
í„ξ‹’xvîYVEöæ«6§]|²½ýj‡Ï#åËßjv™-k.u\ŠÈ›O–#ó!ЊúÊmcLþ-¹ïšÆÔ4ïkùñE¸ÿ0h±j§‘òù
Ԉ켯íº×ÂÝã/g:»¸âïþ=³-²û?áHÑI3ŒKÙW¨ÍNºŽî-¶_Ã#IÙ¸{Tiû¸>â€3ÿu7#V[àüš‘í•ùT[9\Ó’ª?oçJ©ù…69Ùxß÷¹©ö¼
|ÊOµ°™W##êàÔ²iw®»–uõ5Eíåˆà«ôÅHä¯"‘\PˆÙŽ>ïÖœÖò'¡÷†^Ž#3Sg+ÀéYžt±uBG>=H'ÞB>”À¾7ƒè)É#)åsU×S‰‡R>µ"\£ô4‹é"ç=D/ÿ-
š¦¼ô©àuCó'´‰ Ë7çPëÑ¿Z½åÛÌ>\Mk
&ʱœÒ0ê*#)ÏAV怩#Bd`^):ܲ¯ü*îÛERk†^ù¦CiÃsõ¦
ší¹Îj¬“*øhf﶑¬†CqíH’ëëIæsŒŠÐ{=ÍW{
:dÓ¸aÐœýjXîæCÃA:æ”CŽÿe5iG£}h7I7ßCüê¬8èqP–t<Ò…©£¸MÄúbª¼EM'ÚJš‘oPýôϽHˆ2GµZ¶¾T
H/Ò¢yb“§ò¦R9ÓC6,n...
I'm using images as a sample at the moment but the finished php should eventually allow to display PDF documents. If it's any help I'm using phpmyadmin and MySQLi.
As the comments suggest, storing the file location in the database is much better than storing the file's data in the database. BUT if you need to store the file contents in the database for some reason, there are two methods. One is using the HTML data: URL and the other is having a PHP file as the middle man.
For the PHP Middle Man method, look at the answer above mine where it sets the header information and then echo's the file contents. The file extension doesn't matter since browsers refer to the content-type header instead of file extensions.
For the Data URL method, which can be placed directly in your code easily check out http://en.wikipedia.org/wiki/Data_URI_scheme
<?php
// Array of valid Mime Types, prevents possible XSS methods.
$valid_mimes = array(
'image/png',
'image/gif',
'image/jpeg'
);
// Obtain Mime Type using finfo
// Finfo allows for strings instead of file path
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->buffer($row['file']);
// Check if mime is in our $valid_mimes array
if(!in_array($mime,$valid_mimes)) {
// Handle Error
echo 'Illegal Mime Type: '.$mime;
die();
}
$b64 = base64_encode($row['file']);
echo '<img src="data:'.$mime.';base64,'.$b64.'" />';
?>
You cant output <img src=\ as an output it will corrupt the image file and
Please use getImage.php as a different file to output images or verify that no output is printed before,after or in mid of image else it will corrupt the image.
if(isset($_GET['id'])){
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo $row['file'];
}
Trying to loop through a test database with images (I know many say not to do this, but it simplifies so much in terms of backups, etc.). I can get the result I want by creating image files on the fly, but there must be a way to do this without creating files. Can someone suggest a syntax I can use without having to create these image files?
Here is what I have working:
<?php
// configuration
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "SELECT id,title,author,description,cover FROM books";
$q = $conn->prepare($sql);
$q->execute();
$q->bindColumn(1, $id);
$q->bindColumn(2, $title);
$q->bindColumn(3, $author);
$q->bindcolumn(4, $description);
$q->bindColumn(5, $cover, PDO::PARAM_LOB);
while($q->fetch())
{
file_put_contents($id.".png",$cover);
echo ("<img src='".$id.".png'><br />, $title, $author, $description,<br/>");
}
?>
I am thinking that we should be able to eliminate the "file_put_contents.." line and in the echo line, replace the
<img src='".$id.".png'>"
with some php/pdo statement that retrieves the blob and puts it in the proper format. Tried a few things, but have not been successful.
Any suggestions would be helpful!
you do not need to do it in 2 separate files and invoke the script in src attribute of img tag.
Try do this
echo '<img src="data:image/'.$type.';base64,'.base64_encode($image).'"/>';
Where $type is the extension of the image(.png/.jpeg/....) and $image is the binary of the image that you have stored in your DB. in my case I pull the value of the type of image from the db, if you store always the same extension(ex jpeg) you can simply write:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
the method is an alternative to do that with 2 files.
You need to write code in 2 files. As when browser gets <img src="path/to img_file"> code (or code like <script src="....">), etc, a separate request is sent to server by browser at src path value. So, you also need to create file img_file.
Pseudo code is below,
Firstfile.php
<?php
..................... Other code
while($q->fetch())
{
?>
<img src="image.php?id=<?php echo $id; ?>"><br />,
<?php
echo "$title, $author, $description<br/>";
}
?>
And at image.php file,
header('Content-Type: image/png');
$id = $_GET['id'];
$query = " ..... where id = '".$_GET['id']."'";
//You need error handling if $_GET['id'] is integer and valid value. I am not writing this error handling code
if($q->row_count!=1){
//no database row found. It's error.
echo "Show no image found image. As browser expects image you can not write text here";
die;
}
//it's valid image, else code is already terminated by above die.
while($q->fetch())
{
//show image
echo $cover;
}
?>
I wrote Pseudo code exact code depend on requirements.
If you want .png extension, you can use Apache rewrite. Google it you will get it.
When first time i wrote answer, I missed last php ending tag. By the way, last ending tag ?> is optional in php.
If you are getting X , it seems first file code is ok. As imag_file is not at server, it's showing 404 error. View source to check whether $_GET['id'] is correct. If id is correct, then you want to write at file img_file.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,'">';
?>
I've set up a system to display everyone's name, email address and phone number from Active Directory however I can't get the 'thumbailPhoto' to work.
I have searched around on the internet but haven't been able to find if this is possible or at the very least what format is returned from Active Directory.
I am currently using the adldap class so if it is possible to use this that would be ideal.
Thanks in advance.
Edit:
I can retrieve the data in the thumbnailPhoto attribute and if I dump them straight to the browser I get something like this:
ÿØÿàJFIFððÿá
PExifII*bh~†(2Ži‡¢XCanonCanon EOS 5D Mark
IIIðð2013:05:19 17:35:31š‚à‚è"ˆ'ˆ 0230ð’
’ ’ (’0’8’ ’ ’#‘’11’’11 0100
ÿÿ¢H¢P¢¤¤¤¤ 2013:04:17
11:44:522013:04:17 11:44:52H¹o#B¬ †
è»dnäWµ˜:̦®(¶’
HHÿØÿàJFIFÿÛC $.'
",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀ–d"ÿÄ
ÿĵ}!1AQa"q2‘¡#B±ÁRÑð$3br‚
%&'()456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ
ÿĵw!1AQaq"2B‘¡±Á #3RðbrÑ $4á%ñ&'()
That isn't all of it but it is a very long string, I am presuming is some sort of binary string?
This seems to be a JPEG-File, so you should be able to send that data together with the appropriate mime-type to the browser. It should be possible to output that image with something like:
<img src="data:image/jpeg;base64,<?php echo base64_encode($imageString); ?>"/>
But it might also be possible to save files of any image format into that thumbnailPhoto attribute. Therefore, I would put the content into a temporary file that will then be served directly from the server. You will need to pass the file through finfo to get the correct mime-type.
So you might do something like this:
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $imageString);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
echo '<img src="data:' . $mime[0] . ';base64,' . base64_encode($imageString) . '"/>';
Try the code below. It is an adaptation of the answer above.
<?php
$result = ldap_search($ad , $dn , $filter, $attributes);
$aduser = ldap_get_attributes($ad, ldap_first_entry($ad,$result));
?>
<img src="data:image/jpeg;base64,<?php echo base64_encode($aduser['thumbnailPhoto'][0]); ?>" />
when you store the photo data into ldap i.e. "jpegphoto" attribute it should be done by using encode base64.
Reading the attribute is already decoded on fly. Hence I would use something less modified code
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $imageString);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
header("Content-Type: $mime");
echo $imageString;
This is direct php image write example
you can directly use it under tag img i.e.
<img src="example.php" />