is it possible to create and display a picture file from dataURL received by POST?
Something like:
<?
$imgstr = $_POST["imgdata"]; //data:image/png;base64,.... etc (it's always PNG)
echo base64_decode($imgstr); // idk what this really does
?>
I can't use <img> tag to display it. It needs to act like a "normal" image file.
Yes, try:
<img alt="Base64 Image" src="data:image/png;base64,{$imgstr}" />
Edit: make sure you clean up your $_POST, so people do not insert dangerous junk...
If e.g. your input is
// Red dot graphic, stolen from Wikipedia
$imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
Then you can do what you want with
// Grab the MIME type and the data with a regex for convenience
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}
// Decode the data
$content = base64_decode($matches[2]);
// Output the correct HTTP headers (may add more if you require them)
header('Content-Type: '.$matches[1]);
header('Content-Length: '.strlen($content));
// Output the actual image data
echo $content;
die;
You must set correct header before echo.
header( 'Content-Type: image/jpeg' );
Related
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();
$bin_string = file_get_contents($_FILES["file"]["name"]); // image reading
$hex_string = base64_encode($bin_string); // encoded image
Saving into database and then retrieving back...
$decoded= base64_decode($message); // decoded image....
In HTML:
<?php header("Content-Length: " . strlen($decoded));
header('Content-Type: image/png'); ?>
<?php echo $decoded ?>
But this is not working.... what else is needed?
Here is the output of base64_encode($bin_string) :
/9j/4AAQSkZJRgABAgEASABIAAD/7Q1oUGhvdG9zaG9wIDMuMAA4QklNA+0KUmVzb2x1dGlvbgAAAAAQAEgAAAABAAEASAAAAAEAAThCSU0EDRhGWCBHbG9iYWwgTGlnaHRpbmcgQW5nbGUAAAAABAAAAHg4QklNBBkSRlggR2xvYmFsIEFsdGl0dWRlAAAAAAQAAAAeOEJJTQPzC1ByaW50IEZsYWdzAAAACQAAAAAAAAAAAQA4QklNBAoOQ29weXJpZ2h0IEZsYWcAAAAAAQAAOEJJTScQFEphcGFuZXNlIFByaW50IEZsYWdzAAAAAAoAAQAAAAAAAAACOEJJTQP1F0NvbG9yIEhhbGZ0b25lIFNldHRpbmdzAAAASAAvZmYAAQBsZmYABgAAAAAAAQAvZmYAAQChmZoABgAAAAAAAQAyAAAAAQBaAAAABgAAAAAAAQA1AAAAAQAtAAAABgAAAAAAAThCSU0D+BdDb2xvciBUcmFuc2ZlciBTZXR0aW5ncwAAAHAAAP////////////////////////////8D6AAAAAD/////////////////////////////A+gAAAAA/////////////////////////////wPoAAAAAP////////////////////////////8D6AAAOEJJTQQIBkd1aWRlcwAAAAAQAAAAAQAAAkAAAAJAAAAAADhCSU0EHg1VUkwgb3ZlcnJpZGVzAAAABAAAAAA4QklNBBoGU2xpY2VzAAAAAHMAAAAGAAAAAAAAAAAAAABIAAAAoAAAAAkAYQBpAHIAdABhAHMAdABpAGMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAKAAAABIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADhCSU0EERFJQ0MgVW50YWdnZWQgRmxhZwAAAAEBADhCSU0EFBdMYXllciBJRCBHZW5lcmF0b3IgQmFzZQAAAAQAAAACOEJJTQQMFU5ldyBXaW5kb3dzIFRodW1ibmFpbAAACcEAAAABAAAAcAAAADIAAAFQAABBoAAACaUAGAAB/9j/4AAQSkZJRgABAgEASABIAAD/7gAOQWRvYmUAZIAAAAAB/9sAhAAMCAgICQgMCQkMEQsKCxEVDwwMDxUYExMVExMYEQwMDAwMDBEMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQ0LCw0ODRAODhAUDg4OFBQODg4OFBEMDAwMDBERD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pVMVdir//W9UkgCpNBiqX3Wv6Na7TXcfL+RCZG/wCBTk2SECVQ8nma2EfO3sr668FitZVJ+mURr+OEYz3gItKbjzV51lYrpnk+dl7S315a2y/8DG1w/wDwuWjFDrL7EWVnqfm3dJ8MGiaZXu8lzeOPoVYF/wCGxrCP50v9iu6Fl8o/mZd73Pnj6qD1jstOgQD5NI0jZPxsQ5Q/00kUe9QP5TXt2Kax5z16+XvHHcJaof8AYxIMP5sDlCATwtR/kH+WteV3ZXGoP3e7u7iUn/hxhOvy9DXwRwBGw/kr+VcJHDy3aGnQuHf/AIkxys67Mf4ingCb2nkDyPZ0+raBp8ZHQi2iJ+8rlZ1GQ85FPCE0h0fSYKejZW8VOnCJF/UMhxk9VpFKiqKKAB7CmRS3irsVaZEYUZQw9xXG1QVzoWiXQIudPtpweokhjb9YOSE5Dqikhv8A8pvy1v2LXPlyxJPdIhEf+SfHLo6vKOUijhC7y3+WXlDyzqZ1DQbaSxkeNopIEmlaBlYg7xuzLUEbMMGXUzyCpbqIgMqyhk7FX//X9UMqsKMAw8DvirlRFFFAUe22Kt4q7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FXYq7FX/2Q==
1)
$_FILES["file"]["name"] contains only name of uploaded file. Real temporary path of uploaded file on your server is stored in $_FILES["file"]["tmp_name"].
$bin_string = file_get_contents($_FILES["file"]["tmp_name"]);
2)
There can be some invisible character printed out before or after the image.
Please ensure that <?php is the first thing on the first row of your file and, for simplicity, remove all other <?php and ?>, including the last one. You can add die; on the last row to end the script to ensure that nothing else is added to the end of image.
I got the solution...
simply convert the image using
$bin_string = file_get_contents($_FILES["file"]["tmp_name"]); // image reading
And then for converting string back to image use the following :
" />
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'];
}
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" />
I tried to link stored image(blob data) inside MySQL DB to PHP but only thing I achieved was whole page of characters. This is what I did:
$query = "SELECT image FROM uploads WHERE id = {$id}";
$image_array = mysql_query($query, $connection);
$row = mysql_fetch_array($image_array);
$image = $row['image'];
echo $image;
// echo base64_decode($content);
This displays raw data how it is stored. I would like to link it into HTML tag or atleast display it on page, where I display a lot another stuff to so
header('Content-type: image/png');
is not solution for me.
Any advice?
To show the image correctly you just need to put one header with Content-type: image/png before echo
header("Content-type: image/png");
echo (base64_decode($row['image']));
If you want to place instead in an image tag you just need to use this code
echo '<img src="data:image/png;base64,' . $row['image'] . '" />';
You need to give proper headers, otherwise the page wont know what you're sending it.
// define results into variables
$name=mysql_result($result,0,"file_name");
$size=mysql_result($result,0,"file_size");
$type=mysql_result($result,0,"file_type");
$content=mysql_result($result,0,"file_stream");
// give our picture the proper headers...otherwise our page will be confused
header("Content-Disposition: attachment; filename=$name");
header("Content-length: $size");
header("Content-type: $type");
echo $content;
You should use something that is called 'Inline image'. Use this code to display the image on a page, asssuming the $image variable contains base64 encoded data:
<img src="data:image/png;base64,<?php echo $image; ?>" alt="Larry" />
Source: https://en.wikipedia.org/wiki/Data_URI_scheme