PHP converting an image to a binary file test
15,955
Solution 1
Use $data
instead of $fd
$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($data, $size);
fclose ($data);
Solution 2
As you can see here http://php.net/manual/en/function.fread.php.
So as you can read fread
need a resource generate with fopen
.
In your case:
<?php
$image = "image003.jpg"; // be careful that the path is correct
$data = fopen($image, 'rb');
$size = filesize($image);
$contents = fread($data, $size);
fclose($data);
$encoded = base64_encode($contents);
echo $encoded;
?>
Related videos on Youtube
Comments
-
Renegade Rob almost 2 years
I wanted to try to convert an image to Binary.
I found a script online but it does not work.
Could someone please advise why?
<?php $image="image003.jpg"; $data = fopen ($image, 'rb'); $size=filesize ($image); $contents= fread ($fd, $size); fclose ($fd); $encoded= base64_encode($contents); echo $encoded; ?>
I have an error come up on line 8 and 9
Warning: fread() expects parameter 1 to be resource
and
Warning: fclose() expects parameter 1 to be resource,
-
borracciaBlu about 8 yearsYou should use $data instead of $fd
-
Renegade Rob about 8 years@RichardTheobald Thats the entire code. I found it online and thats the entire script included
-
-
Richard Theobald about 8 yearsThis will not work for the same reason his original code doesn't work;
$fd
is undefined. ;-) -
borracciaBlu about 8 years@RichardTheobald you right i missed the handler in fclose.. i was focus on fread, Thaks ;)