I want to convert image from its url to base64.
Do you want to create a data url? You need a MIME-Type and some other additional information then (see Wikipedia). If this is not the case, this would be a simple base64 representation of the image:
$b64image = base64_encode(file_get_contents('path/to/image.png'));
Relevant docs: base64_encode()-function, file_get_contents()-function.
I got to this question searching for a similar solution, actually, I understood that this was the original question.
I wanted to do the same, but the file was in a remote server, so this is what I did:
$url = 'http://yoursite.com/image.jpg';
$image = file_get_contents($url);
if ($image !== false){
return 'data:image/jpg;base64,'.base64_encode($image);
}
So, this code is from a function that returns a string, and you can output the return value inside the src parameter of an img tag in html. I'm using smarty as my templating library. It could go like this:
<img src="<string_returned_by_function>">
Note the explicit call to:
if ($image !== false)
This is necessary because file_get_contents can return 0 and be casted to false in some cases, even if the file fetch was successful. Actually in this case it shouldn't happen, but its a good practice when fetching file content.
Try this:-
Example One:-
<?php
function base64_encode_image ($filename=string,$filetype=string) {
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
?>
used as so
<style type="text/css">
.logo {
background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>
or
<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
Example Two:-
$path= 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I'm not sure, but check this example http://www.php.net/manual/es/function.base64-encode.php#99842
Regards!
base64_encode
Related
I want to get the image file from my public folder which I stored all of my images, then convert to base64. I will use the base64 image to view it on PDF using pdfmake in dataTables, because my dataTable cell have an Image called avatar, and as I've searched it needs to convert image to base64 to able to view in PDF.
Now I use file_get_contents to retrieve my image, but my page is too much load I guess it's around 5mins, and after throws and error Maximum execution time of 60 seconds exceeded.
{{ file_get_contents( asset('files/user_avatar.png') ) }}
There is difference between svg and (jpg-png-jpeg) when you encoding to base64. You can use basically png extension when you working with png image. But you cant use svg basically. You need svg+xml when you working with svg.
function img_enc_base64 ($filepath){ // img_enc_base64() is manual function you can change the name what you want.
if (file_exists($filepath)){
$filetype = pathinfo($filepath, PATHINFO_EXTENSION);
if ($filetype==='svg'){
$filetype .= '+xml';
}
$get_img = file_get_contents($filepath);
return 'data:image/' . $filetype . ';base64,' . base64_encode($get_img );
}
}
so now
echo img_enc_base64('file_path'); // is your base64 code of image
<img src="<?php echo img_enc_base64('file_path');?>" alt=""> // is your image
file_path example: pics/my_book.png
I'm not friendly with Laraval but I have a tested answer written in PHP
<?php
$path = "files/user_avatar.png";
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
# print to make sure that it is working or not
echo $base64."<br>";
# Or, show it as a clean image
echo '<img scr="'.$base64.'" height="150" width="150">';
?>
Edited:
According to Jin,
Above snippet not working just because of file_get_contents function.
Solution:
Use curl_get_contents() instead of file_get_contents
curl_get_contents()
function curl_get_contents($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
After replacing file_get_contents into curl_get_contents
$path = "files/user_avatar.png";
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = curl_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
# print to make sure that it is working or not
echo $base64."<br>";
# Or, show it as a clean image
echo '<img scr="'.$base64.'" height="150" width="150">';
Still taking too much time to load?
Try to check your file size or try
to check Server-Configuration
Hope it will helpful for you 😊
I think that it should be:
$path = 'files/user_avatar.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.
I need to convert the image URL to base64_encode data using PHP. I am explaining my code below.
<?php
$path='https://www.jquery-az.com/html/images/banana.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64=base64_encode($data);
print_r($base64);exit;
?>
Here I am getting the blank output. Please help me to resolve this issue.
your code is working for me. I suppose the error is that in php.ini is disallowed to open remote urls: http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen set it to true
add this line and check for error message
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$path='https://www.jquery-az.com/html/images/banana.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64=base64_encode($data);
print_r($base64);exit;
Here's code to convert image to base64 format
$path='http:\/\/abcd.com\/pub\/media\/catalog\/product\/\/m\/i\/mi-l32m5-ai.jpeg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
Thanks
Please use the unescaped url in $path variable,
<?php
$path='http://abcd.com/pub/media/catalog/product//m/i/mi-l32m5-ai.jpeg';
Try this code. It will help you.
According to his question, he needs to encode the image path. First, check if the image exists, if yes then encode its path .
$path = 'your-file-path';
$file = 'your-file';
$image_with_path = $path.'/'.$file;
if(file_exists($image_with_path)){
$base64 = base64_encode($image_with_path );
}
I want to load an image to PDF from generated image.
I had set isRemoteEnabled to true and
generated QRCode working fine
Here is my code.
$this->load->library(array('pdf', 'ciqrcode'));
$data = array('qrlink' => base_url('generateQR?text=123'));
$this->pdf->set_paper('folio');
$this->pdf->loadHtml($this->load->view('pdfoutput', $data, true));
$this->pdf->set_base_path(base_url());
$this->pdf->render();
$this->pdf->stream('QR-PDF', array("Attachment" => false));
And here is my view
<img src="<?= $qrlink ?>" alt="QRcode" width="150px">
But the output say Image not found or type unknown.
So what should I do?
Thanks in advance.
Cheers.
I had a similar issue and after many hours searching the inter-web, I found out (thanks to Atiruz ) that Dompdf does NOT render images well with remote urls e.g. http://your-domain.com/com/images/img.png" /> always gave me the same error [Image not found or type unknown]. In my case***strong text*** I had to use a base64 encoded image and it seemed to have resolved my issue.
I wrote a small snippet that can encode your image into base64 and return a string to use inside your tag.
Here is how to use the base64 encode data as your img src
//Use a valid base64 encoded data string
<img src="your-base64-encoded-image-string" />
Here is the snippet to convert your image into a base64 encoded image data
function encode_img_base64( $img_path = false, $img_type = 'png' ){
if( $img_path ){
//convert image into Binary data
$img_data = fopen ( $img_path, 'rb' );
$img_size = filesize ( $img_path );
$binary_image = fread ( $img_data, $img_size );
fclose ( $img_data );
//Build the src string to place inside your img tag
$img_src = "data:image/".$img_type.";base64,".str_replace ("\n", "", base64_encode($binary_image));
return $img_src;
}
return false;
}
I hope this helps someone out there!
I had the same issue with pdf and i solved using this function
function encode_img_base64($img_path = false): string
{
if($img_path){
$path = $img_path;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
return 'data:image/' . $type . ';base64,' . base64_encode($data);
}
return '';
}
When I echo the following:
$im_dec = base64_decode($row['image']);
I obtain the desired URL:
https://www.ft.com/__origami/service/image/v2/images/raw/http%3A%2F%2Fprod-upp-image-read.ft.com%2F1263ad72-2d9a-11e7-9555-23ef563ecf9a?source=next&fit=scale-down&compression=best&width=210
Then I use this URL to be the src of my img:
$newImage = $dom->createElement('img');
$newImage->setAttribute("src", $im_dec);
$newImage->setAttribute("class", "articleImage");
$newTitle->appendChild($newImage);
And when I check the src attribute in my html document, I get a modified url where
& is replaced by & for example and many more weird stuff..
Some characters were modified and I don't know how to avoid it. I tried many things but I thought base64 encoding would work...
Help please!
You can convert an image to base64 encoding with the following example:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I want to hide image path from website. To do that first I did this:
<?php
// get image path
$path = 'images/profiles/uploads/' . $list['thumbnail'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
?>
But this is very slow, So I try to implement like this, but code is not working:
download.php:
function setImgDownload($imagePath) {
$image = imagecreatefromjpeg($imagePath);
header('Content-Type: image/jpeg');
imagejpeg($image);
}
mypage.php:
<?php include('download.php'); ?>
<img src="<?php setImgDownload('images/Chrysanthemum.jpg') ?>" width="300"/>
If I put function and call function at the same page it's working:
function setImgDownload($imagePath) {
$image = imagecreatefromjpeg($imagePath);
header('Content-Type: image/jpeg');
imagejpeg($image);
}
setImgDownload('images/Chrysanthemum.jpg');
How to keep function in separate page?
Try changing your mypage.php to
<?php
include('download.php');
echo "<img src='".setImgDownload('images/Chrysanthemum.jpg')."' width='300'/>"; // calling function inside php
?>
Here, instead creating the HTML element outside php, put it inside php using echo and just escape while calling the php function. This should give you what you need.