GOAL: I'm trying to display an Image into my Laravel 7 view, retrived directly from database.
In my MySQL WORKBENCH:
PROCESS:
As you can see in my controller JobsController, I will select and retrieve the image from database, identified by jobs $job_name.
As you can see here, I tried to dd($job_name) and we can see that BLOB data in $job_image variable. I will pass this Collection object to view and display it directly.
Most SO questions relate to displaying the image using <img src="myFileName"/>.
Problem is I'm not storing it as a file but instead just retrieve and display it directly. I just want to dump all the variables into my view file like other job details.
Solutions tried in my view file.
<img>{{ base64_encode($job_details->job_image) }}</img>. Failed. Output is "/9j/4AAQSkZJRgABAQ".
<img>{{ base64_decode($job_details->job_image) }}</img>. I don't have much understanding about what encoding and decoding happens when data is stored and retrieved from and to the database. Here I decoded the variable. No output.
<img src="{{ $job_details->job_image}}"/>. This is dumb, src attribute expects an PATH.
So there, none of these would turn the variable content into an image.
Please tell me what I am missing here.
Try this
$image = 'your_image_blob_name';
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
echo '<img src="'.$src.'">';
You're almost there. You have to use the base64 string in the src attribute. Make sure you also include the data type and other relevant information at the beginning. See: How to display Base64 images in HTML?
Related
I have this line:
move_uploaded_file($_FILES["img"]["tmp_name"], "uploads/" . "$img_name");
That used to work when I received the image through a direct POST (without JSON.stringify the content).
Now I'm sending the ajax with the image inside of an array stringified, so I'm getting the contents of the array in the PHP file in this way:
$unstringified = json_decode(file_get_contents("php://input"), true);
And then I use:
$title = $unstringified["title"];
$content = $unstringified["content"];
$img = $unstringified["img"];
The problem is that now the move_uploaded_file stop working (seems to be no error but the image doesn't appear saved in the folder anymore). I tried some options like these, but didn't work.
move_uploaded_file($unstringified["img"]["tmp_name"], "uploads/" . "$img_name");
move_uploaded_file($_FILES[$unstringified["img"]]["tmp_name"], "uploads/" . "$img_name");
Any idea to solve this? Should I "convert" the image in any format until putting it in the array I will stringify? or I have to get the image in another way in the PHP file?
Thanks a lot in advance.
Leandro.
I wanted to pass the image inside a JSON because always that I've tried to pass and image with other string variables with formdata, I've always got an error, even playing with all posible variables of dataType, contentType , Cache, etc, and researching through lot of answers here. I couldn't find a solution to use form data to pass all togheter.
What I found I can do is to pass all inside within a JSON object without getting errors, so that's why I wanted to receive the image in PHP under this format and save it in this way.
But after trying lot of ways, again, and couldn't find a solution for this, I gave up, and use 2 separate sends, one json object with all the strings inside, and one formdata with only the image (if I don't add another variables like strings, there's no problem).
I'm sure it's not the best way, but it's what I can do.
Thanks all!
How can I display an image and pass it as an input parameter in an executable in php without saving the image in a folder. The user gives the image path as input and I am using ajax to display the image when it is selected when I save it to a folder it works but how can I display it without saving it in a folder? My code now is
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
//echo "Stored in "."upload/".$_FILES["file"]["name"];
echo "<img src='upload/".$_FILES["file"]["name"]."' class='preview'>";
I tried
<img src=$_FILES["file"]["tmp_name"]. class='preview'>
but it didnt work. As I will have thousands of input from thousands of user I dont want to save it. Is there any optimised and efficient method to do this?
I think, its not possible to show image without saving it. You could try to save the image in temp folder on the server side and clean this folder periodically to avoid much space consumption.
The src attribute of the <img> tag should be an URL accessible by the client.
You try to give a local path (ex: path/to/your/file.jpg) of a temporary file as URL, it will not working.
info: The uploaded image is save on the local disk on a temp directory, and could be deleted by PHP later.
If you want to show the image without moving it at a place reacheable by a URL, you can try to load its content as base64 content
$imagedata = file_get_contents($_FILES["file"]["tmp_name"]);
$base64 = base64_encode($imagedata);
and use in your HTML
<img src="data:image/png;base64, <?php echo $base64; ?>" />
I don't think you can show the image without saving it.
You need to save the file either to the filesystem or to memory if you want to later output
Your problem here is that $_FILES only exists in the script that the image was sent to. so when you initiate another http request for img source, php no longer has any clue what file your trying to read.
You need a way to tell which image to be read on http request.
One thing you can do is that you can save the file in a place accessible by the client and then just have php delete it after you output it. So once the image is outputted it will be deleted and no longer be existing in the file system.
Another approach would be to get the image from the memory by directly writing the contents to httpresponse.
You can do this way
$image = file_get_contents($_FILES["file"]["tmp_name"]);
$enocoded_data = base64_encode($image);
and when you show your image tag :
<img src="data:image/png;base64, <?php echo $enocoded_data ; ?>" />
Hope any of these helps you
I want to store the canvas image into a blob field.
on the server side I receive a base64 encoded string from toDataUrl()
What do I have to do to get it into a blob field?
And how do I display it again in an img tag?
What code do I need to use?
The mysql page is not very clear, and I use PDO prepared statements.
If you really need to store it in blob data, you can do this:
For PHP >=5.2.0, you can use the data:// stream wrapper to retrieve file from a data uri:
$file_in_blob = file_get_contents("data://".$var_containing_the_data_uri);
where $var_containing_the_data_uri should be replaced by the variable containing the data URI, for example $_POST['image']. Then you can insert the $file_in_blob to the database.
When you need to display it in a webpage again, you can:
write a PHP script that retrieves the blob content according to a GET parameter, and use it as an src for the image tag, or
directly use the original data URI obtained from toDataUrl() as the src of the image tag.
If you use method 2, you don't actually need to decode the data URI into blob, but store the data URI directly. (Of course you may be concerned of the data size...)
Method 1 example:
Your HTML:
<img src="img_from_db.php?img=1" />
Your img_from_db.php:
<?php
header('Content-Type: image/png'); // make the browser recognize it as PNG
echo get_image_blob_from_db($_GET['img']); // you may wish to add some checks
Method 2 example:
<img src="<?=get_image_dataURI()?>" />
Let's say I have a user enter the URL of an image.
After URL validation, etc. I want to get the image and store it in a PHP variable. Not the image path, but the actual image itself.
I am adding this image-holding variable in between other strings, so I cannot change use header() before echoing the image. Is it possible to use <img> HTML tags? I really don't want to copy the images to my own server...
How do I:
Store the image in a variable such that,
Echo the image from the variable without changing headers.
Edit:
I said above that I am putting this image inside another variable, e.g.:
$str = "blah blah" . $var_holding_img . "more text";
Is it possible to insert something in the string above that will be replaced with the images? Can parse the variable $str later to replace some random text like "abg30j-as" with the image...
I found an answer to my own question:
First, I created another PHP file, called img.php:
<?php
$url = $_GET['imgurl'];
/*
Conduct image verification, etc.
*/
$img_ext = get_ext($url); //Create function "get_ext()" that gets file extension
header('Content-type: image/' . $img_ext);
echo file_get_contents($url);
?>
Then, in the original PHP file, I used this PHP code:
<?php
$var_holding_img = '<img src="img.php?imgurl=http://example.com/image.png"/>';
$string = "This is an image:<br \>" . $var_holding_img . "<br \>displayed dynamically with PHP.";
echo $string;
?>
This way, the PHP file "img.php" can use the proper headers and the image can be inserted as HTML into any other PHP variable.
How do I:
Store the image in a variable such that,
Echo the image from the variable without changing headers.
You can do this in two ways.
In way one, you serialize the image in a string, and save the string in the session. Which is exactly the same as saving it server side, except that now the session GC should take care of clearing it for you. Then the IMG SRC you use will redirect to a script that takes the image and outputs it as image with proper MIME type.
In way two, if the image is small enough, you can encode it as BASE64 and output it into a specially crafted IMG tag:
http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
This saves you some time in connection, also. Of course the image must be reasonably small.
You can't save the actual image in a variable. Either you save the URL or copy the image (what you obvious don't want) to your server and save the path to the image
See answer 1, you can't echo the image itself, only link it
Edit: Okay obviously you can save images directly to a variable, but I don't recommend you to do this.
No, that isn't possible. If you want to serve something, it has to exist on the server.
I am using OAuth 1.0, I am getting the contacts just fine. Next I fetch an image using the link that is in the contact info. If the user has an image the request works and return a bunch of data. When I echo it I get something like this:
"" ÿÀ``"ÿÄÿÄ<!"12A#Qq‘BRa3‚’±Ñðbrƒ¡Â$%¢³ÿÄÿÄ#!1Q"AaqÿÚ?ôÌìç™pzõWoÂ~vïD±èÐvQNl/žåÐìMCÀƒÚüü¿ ÔLß÷&‹ðKš×aG¥=Ë È
Which I am assuming is the data for the image. Now that I have this, I cant figure out a way to display it.
here is an example of what I am doing:
$consumer = new OAuth($key,$secret);
$image = $consumer->fetch($theImageUrl);
return $image;
The request is working, theres no 400,401, or 404 errors.
I tried doing this already:
<img src="/art/transperantimage.png" style='background: #fff url(data:image/png;base64,<?=$image ?>) repeat-x bottom'/>
and I just ended up with more data jibberish.
I guess my question is how the heck to I display this data?
Per the documentation, this request returns the bytes of the image. So you have three options:
Write a PHP script that outputs those bytes (and only those bytes) directly to the client using the appropriate Content-Type header, which is what #Prowla has in mind. Then point to this script in your <img src="...">.
Write the bytes to a publicly-accessible file on your web server, and then put the URL of that file in your <img src="...">.
Use a data URI, which you seem to have attempted, but forgot that you need to Base64 encode the data first, e.g.:
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image ); ?>" />
While #3 is looks the simplest, #2 is probably the best solution since the image likely doesn't change very often so there's no sense requesting it from the API every single time someone reloads your page. You can just write the image to a file if the file doesn't already exist, and then periodically (e.g. every day or week) check to see if there is a new image and if there is, overwrite the old one.
Before printing out the image set the header content type to something like (depending on the data type):
header('Content-Type: image/jpeg');