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;

?>
Share:
15,955

Related videos on Youtube

Renegade Rob
Author by

Renegade Rob

Learning code and need help. Hence why I am here

Updated on June 04, 2022

Comments

  • Renegade Rob
    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
      borracciaBlu about 8 years
      You should use $data instead of $fd
    • Renegade Rob
      Renegade Rob about 8 years
      @RichardTheobald Thats the entire code. I found it online and thats the entire script included
  • Richard Theobald
    Richard Theobald about 8 years
    This will not work for the same reason his original code doesn't work; $fd is undefined. ;-)
  • borracciaBlu
    borracciaBlu about 8 years
    @RichardTheobald you right i missed the handler in fclose.. i was focus on fread, Thaks ;)