Basically image/ document in jpf / png / pdf format needs to be converted into base64Binary and passed as json request.
Have seen a lot of code on the web but all are in Java or ASP. There is nothing I could find that would help with reading file and outputting base64binary value in PHP.
You could use the following code. Assuming you can use file_get_contents function,
$file_type = pathinfo($path, PATHINFO_EXTENSION);
$contents = file_get_contents($file_type);
$encoded = 'data:image/' . $file_type . ';base64,' . base64_encode($contents);
or you can use base64_encode function. Base64-encoded data takes about 33% more space than the original data.
$data = file_get_contents($contents);
$encoded = base64_encode($data);
echo $encoded;
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 );
}
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);
Can I safely assume that the size (in bytes) of a PNG image file created with the following PHP code:
$f = fopen("newImageFile.png", 'w');
$content = base64_decode(substr($dataURL, strpos($dataURL, ',') + 1));
fwrite($f, $content);
where $dataURL is posted from HTML's canves.toDataURL(), exactly equals strlen($content)?
You could use getimagesizefromstring() If you have a newer php version.
But since you are decoding you could use this as well.
$uri = 'data://application/octet-stream;base64,' . base64_encode($data);
getimagesize($uri);
I'm saving some of my image in to mysql database using base64_encode.
now I want to restore them back to file system.
How can I do that?
Edit...!
Ok, I did not explain enough.
I use this code to encode my image and save them in to a blob table:
function base64_encode_image ($imagefile) {
$imgtype = array('jpg', 'gif', 'png');
$filename = file_exists($imagefile) ? htmlentities($imagefile) : die('Image file name does not exist');
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($filetype, $imgtype)){
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
} else {
die ('Invalid image type, jpg, gif, and png is only allowed');
}
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
and use this code to show my image in browser:
if (!isset($_GET['id']) && !ctype_digit($_GET['id'])){
die('Error');
} else {
require_once( addslashes(dirname(dirname(__FILE__)) . '/config.php') );
require_once( addslashes(dirname(__FILE__) . '/Functions.php'));
$row = mysql_fetch_array(mysql_query ("SELECT `id`,`cover_small` FROM `om_manga` WHERE `Active` = '1' AND `id` = '".sql_quote($_GET['id'])."'"));
if (isset($row['id'])){
header("Content-type: image/jpeg");
readfile($row['cover_small']);
} else {
die('Error');
}
}
Now i want them back to a jpg file.
The size of all those image are less then 3kb.
Use PHP's base64_decode() function to convert the encoded data back to binary.
Since base64_decode returns a string, you can use file_put_contents() to write the decoded contents to a file.
It makes me wonder why you're storing the image base64 encoded if you're not using it in that format. You could just as easily store the image in binary format in a binary blob column.
Base64 encoding adds a 33% character overhead (not bytes).
Edit for revised question
The answer to your second question is subjective without context. Without knowing the details of your system, I can't recommend whether you should extract the images.
Decode it the same way you encoded it...
base64_decode()
You might want to store the file extension of the image when writing it to the database so that you can restore it accurately. Just concatenate the new name with the existing extension.
What you should so is something similar to this :
// Retrieved values from database
$encodedImg = $sqlResult['encoded_img'];
$ext = $sqlResult['encoded_img_ext'];
// Concatenate new file name with existing extention
// NOTE : This parameter is a full path. Make sure that the folder
// you are writing the file to has the correct permissions allowing the
// script write access.
$newImagePath = "/some/path/on/the/servers/filesystem/";
$newImageName = $newImagePath."decoded_image.".$ext;
// Saving the decoded file with the new file name.
file_put_contents($newImageName, base64_decode($encodedImg));