Php convert file to binary

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?


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,

In this article, we will discuss how to convert a raw image to a binary image in PHP.

First of all, we will discuss what exactly a binary image is.

What is a binary image?

A binary image is a 64bit encoded binary data that takes 33% more data than the original image. It is basically applied to images with less size for faster loading of the image.

How to convert to a binary image in PHP

In PHP, the base64_encode() method converts the original image to a binary image. It needs the base URL of an image to perform the task.

You may also learn: How To Add text to image in PHP

Syntax:-

base64_encode($image);

The example is as follows,

Output:-

iVBORw0KGgoAAAANSUhEUgAAAMIAAACpCAMAAABODBKaAAAAOVBMVEX//////+Xd/////+JvOLBUwf+V4f+5gLCVXrD/wssVOMu5////4dhFOLAVXthvwv9FovLdor0VgOWHRjGwAAAABHRSTlMAAAAAs5NmmgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAAEgAAABIAEbJaz4AAANQSURBVHja7ZzJttwgDESdgRhnxPn/j80iq7YFxqIoeO6qdR/RFxAGJLQskiRJkiRJkiRJkiRJ76FPX8OLvuV/ulb/kqcYzqpHGM+xBVM3EUL4/mMQwM9fAYQQwu/PIwhy/8aFEMIfPkEMWISQJiJwIrDHofRXvAjcpWkLPRCYPn38loEQmFNpD30QiMMQOyHwhiH7TWtGSCyEi3n03gg0Z1i7IdCcIfZDSByCrDf/rbexzohwt3Hbyo1egCPc7z7zE09CsDZInnOXZYe0JG2g3rOGYSBCAiGQTtHWl821nsepEFynlXE3Mjuq84TQoBWFAJuRQnhvhG0mBN9HVQhCEMJ/WQePYQi+k4qFwDn/RyE8CcE681AQrIZTT0tf4AjW8PsQrPGkIFiruXP466akEAzBTv+1xzY8AvC4uFb1BhzB8mbv1UndgMIRrJ7zIpix39OIUhC8l7nmBfPJGBrBDAwkpzE7fn2cSmAEO8zm3iGb8aLjtMQi2AT+i9Aqe0iEXN5CclvMxbxe5hIOwZVChTCKQSgGKluCSzUpNQSEpuNuheX+CG0RvmI+BwmhNTq2D0dojyytoxEA9z5XxvsiYKJ7+0AEVJR4G4aQMABLdl36QKOQm0kfxxey/qwVqbKVB3wXmv2htNFj7ZFSk+Vi7rR2qvUNtWxVy4nHSIQyRsMw7BVGocf/TIJqgiO8DCzjBsOPUPWqjHGP5F9XzcnZ9x4pM5fcATIT4ehaaARQnm3BWPc7VbPjvAiDbrZRibY5W2fHwkd5Yk2zdbIWh3T61dSBqrrMNk7EExdro6QLA1NwgHOyGaFr3BkvYPJHXQLDzAi4hJRhfTcsmQeHMFVK1QMQcIltD8iQFAIb4QHZwkIQwkEPeEXygLc8vpafiUB64/kAhJ7PVIXQguDZIyOTdm8K9erc6oqBD+c9G72BCHZ87G7j89XBuNc+oqBJiy7KbBVd8qqoT+IgXJW1aUFgVebZ+yGw6s5t3RBo9TAvnKEBgeTNy5UzNCDwCudtnRCYdVVjH4TEIygPgxuBWxd27YFALjIc8QjsuraFhdWJMFNlXh/CkFLVGxBhTIXnxfNGDP2qDKGbR3jgS2OsoheBtyeSJEmSJEmSJEmSJEkaqH+bT4RNYLoIXAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOC0wNy0xMFQwOTowNTo1MS0wNTowMGAO7pQAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTgtMDctMTBUMDk6MDU6NTEtMDU6MDARU1YoAAAAAElFTkSuQmCC

Note:-

  • In the above script, file_get_contents() method load an image from a path.
  •  file_get_contents() method can also load an image from a link.

Example of Image from a path is as follows,

$image_path=file_get_contents('D:/PICS/Pexels/photo-814194.jpeg');

In this way, we can convert an image to binary from raw image using PHP. If you have any doubts about this article, leave a comment below.

See also,

  • Decimal to Binary conversion in JAVA

Create a Free Account

Sign up to unlock all of IQCode features:

  • Master useful skills
  • Improve learning outcomes
  • Share your knowledge

Sign up Email Password

Or sign up with

By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.

    Table of contents
  • Convert PHP file to binary
  • PHP convert Image file to binary string
  • PHP converting an image to a binary file test
  • How to convert image to binary string using php and file upload?
  • Convert string to binary then back again using PHP
  • Converting string to binary and binary to string with PHP
  • How to convert an image to binary image in PHP?
  • Hex2bin

Convert PHP file to binary

// this needs to match the compiler version that php was compiled with
#define _CRT_SECURE_NO_WARNINGS
#define PHP_COMPILER_ID "VC14"

#pragma once
/* You must include config.w32.h first */
#include "win32/config.w32.h"

#include "php.h"

ZEND_FUNCTION(ReturnString);

zend_function_entry Project1_functions[] =
{
    ZEND_FE(ReturnString, NULL)
    {
        NULL, NULL, NULL
    }
};

zend_module_entry Project1_module_entry =
{
    STANDARD_MODULE_HEADER,
    "Project1 Module",
    Project1_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET, STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(Project1)

ZEND_FUNCTION(ReturnString)
{
    zval* value;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE)
    {
        RETURN_FALSE;
    }

    convert_to_string(value);

    RETURN_STRING(Z_STRVAL_P(value), true);
}
The script is quite simple:


PHP convert Image file to binary string

CREATE TABLE images (
    image_id int,
    image blob 
    PRIMARY KEY (image_id));
*

$sql = 'INSERT INTO images VALUES (1, \'' . $encoded_data . '\')';
$fp = fopen($_FILES['file']['tmp_name'], 'r');
$db_img = fread($fp, filesize($_FILES['file']['tmp_name']));
$db_img = addslashes($db_img);
$db_img = base64_decode($db_img);
$sql = "INSERT INTO images VALUES (1,'$db_img')"

PHP converting an image to a binary file test

Warning: fread() expects parameter 1 to be resource
Warning: fclose() expects parameter 1 to be resource,
$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($data, $size);
fclose ($data);

How to convert image to binary string using php and file upload?

function img_to_bin($file, $scale = 100, $fudge = 0) {

    if (!is_int($scale)) {
        throw new InvalidArgumentException('Scale argument invalid expecting int, got: '.gettype($scale));
    }

    $info = getimagesize($file);
    $mime = $info['mime'];

    switch ($mime) {
        case 'image/jpeg':
            $image_create = 'imagecreatefromjpeg';
            break;

        case 'image/png':
            $image_create = 'imagecreatefrompng';
            break;

        case 'image/gif':
            $image_create = 'imagecreatefromgif';
            break;

        default: 
            throw new InvalidArgumentException('Unsupported image type: '.$mime);
    }

    $return = null;

    $img = $image_create($file);
    $img = imagescale($img, $scale, $scale);

    $width = imagesx($img);
    $height = imagesy($img);

    for ($y=0; $y < $height; $y++) {
        $line = [];
        for ($x=0; $x < $width; $x++) {
            // get current pixel colour
            $rgb = imagecolorat($img, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8 ) & 0xFF;
            $b = $rgb & 0xFF;
            $pixel = ($r + $g + $b)/3;

            // value above 0(white) is 1 
            if ($pixel > $fudge) {
                $line[] = "1";
            } else {
                $line[] = "0";
            }
        }

        $return .= implode('', $line).PHP_EOL;
    }
    return $return;
}

echo img_to_bin("./face.png", 50).PHP_EOL;
00000000000000000000000000000000000000000000000000
00000000000000000000011111111100000000000000000000
00000000000000000011111111111111100000000000000000
00000000000000011111111111111111111100000000000000
00000000000000111111111111111111111110000000000000
00000000000011111111111111111111111111100000000000
00000000000111111111111111111111111111110000000000
00000000001111111111111111111111111111111000000000
00000000011111111111111111111111111111111100000000
00000000111111111111111111111111111111111110000000
00000001111111111111111111111111111111111111000000
00000011111111111111111111111111111111111111100000
00000111111111111111111111111111111111111111110000
00001111111111111111111111101111111111111111111000
00001111111111100111111111000111111111111111111000
00001111111111000111111111000111111111111111111000
00011111111111000111111110000111111111111111111100
00011111111111000111111110001111111111111111111100
00011111111111101111111111011111111111111111111100
00011111111111111111111111111111111111111111111100
00011110011111111111111111111111111111011111111100
00011110011111111111111111111111111111001111111100
00001111101111111111111111111111111110011111111000
00001111110111111111111111111111111101111111111000
00000111111011111111111111111111111011111111110000
00000111111100111111111111111111110111111111110000
00000011111110011111111111111111001111111111100000
00000011111111100111111111111110111111111111100000
00000001111111111001111111111001111111111111000000
00000000111111111110000000001111111111111110000000
00000000011111111111111111111111111111111100000000
00000000001111111111111111111111111111111000000000
00000000000111111111111111111111111111110000000000
00000000000011111111111111111111111111100000000000
00000000000000111111111111111111111110000000000000
00000000000000011111111111111111111100000000000000
00000000000000000011111111111111100000000000000000
00000000000000000000001111111000000000000000000000
00000000000000000000000000000000000000000000000000

Convert string to binary then back again using PHP

// Convert a string into binary
// Should output: 0101001101110100011000010110001101101011
$value = unpack('H*', "Stack");
echo base_convert($value[1], 16, 2);

// Convert binary into a string
// Should output: Stack
echo pack('H*', base_convert('0101001101110100011000010110001101101011', 2, 16));
$bin = decbin(ord($char));
$char = chr(bindec($bin));
$string = 'my binary string';
$binary = b'my binary string';
$string = $binary; // "convert" binary string into string
$binary = $string  // "convert" string into binary string
$hex = bin2hex($bin); // It will convert a binary data to its hex representation

$bin = pack("H*" , $hex); // It will convert a hex to binary
$bin = hex2bin($hex); // Available only on PHP 5.4
echo bindec("00000001") . "\n";
echo bindec("00000010") . "\n";
echo bindec("00000100") . "\n";
echo bindec("00001000") . "\n";
echo bindec("00010000") . "\n";
echo bindec("00100000") . "\n";
echo bindec("01000000") . "\n";
echo bindec("10000000") . "\n";
echo bindec("01000001") . "\n";

# big binary string
echo bindec("111010110111011110000110001")."\n";
1
2
4
8
16
32
64
128
65
123452465
# convert to binary strings "00000001"
echo decbin(1) . "\n";
echo decbin(2) . "\n";
echo decbin(4) . "\n";
echo decbin(8) . "\n";
echo decbin(16) . "\n";
echo decbin(32) . "\n";
echo decbin(64) . "\n";
echo decbin(128) . "\n";

# convert a ascii character
echo str_pad(decbin(65), 8, 0, STR_PAD_LEFT) ."\n";

# convert a 'char'
echo str_pad(decbin(ord('A')), 8, 0, STR_PAD_LEFT) ."\n";

# big number...
echo str_pad(decbin(65535), 8, 0, STR_PAD_LEFT) ."\n";
echo str_pad(decbin(123452465), 8, 0, STR_PAD_LEFT) ."\n";
1
10
100
1000
10000
100000
1000000
10000000
01000001
01000001
1111111111111111
111010110111011110000110001
var bytes = new byte[] { 0x41, 0x42, 0x43 };
$myBytes = "414243";
$data = pack('H*', $myBytes);
class blob
{
    function __construct($hexStr = '')
    {
        $this->appendHex($hexStr);
    }

    public $value;

    public function appendHex($hexStr)
    {
        $this->value .= pack('H*', $hexStr);
    }

    public function getByte($index)
    {
        return unpack('C', $this->value{$index})[1];
    }

    public function setByte($index, $value)
    {
        $this->value{$index} = pack('C', $value);
    }

    public function toArray()
    {
        return unpack('C*', $this->value);
    }
}
// Construct a blob with 3 bytes: 0x41 0x42 0x43.
$b = new blob("414243");

// Append 3 more bytes: 0x44 0x45 0x46.
$b->appendHex("444546");

// Change the second byte to 0x41 (so we now have 0x41 0x41 0x43 0x44 0x45 0x46).
$b->setByte(1, 0x41); // or, equivalently, setByte(1, 65)

// Dump the first byte.
var_dump($b->getByte(0));

// Verify the result. The string "AACDEF", because it's only ASCII characters, will have the same binary representation in basically any encoding.
$ok = $b->value == "AACDEF";
function binary_encode($str){
    
    # Declare both Binary variable and Prepend variable
    $bin = (string)""; $prep = (string)"";
    
    # Iterate through each character of our input ($str) 
    for($i = 0; $i < strlen($str); $i++){
        
        # Encode The current character into binary
        $bincur = decbin( ord( $str[$i] ) );
        
        # Count the length of said binary
        $binlen = strlen( $bincur );
        
        # If the length of our character in binary is less than a byte (8 bits); Then
        # For how ever many characters it is short;
        # it will replace with 0's in our Prepend variable.
        if( $binlen < 8 ) for( $j = 8; $j > $binlen; $binlen++ ) $prep .= "0"; 
        
        # Build our correct 8 bit string and add it to our Binary variable
        $bin .= $prep.$bincur." ";
        
        # Clear our Prepend variable before the next Loop
        $prep = "";

    }

    # Return the final result minus the one whitespace at the end
    # (from our for loop where we build the 8 bit string
    return substr($bin, 0, strlen($bin) - 1);

}

function binary_decode($bin){
    $char = explode(' ', $bin);
    $nstr = '';
    foreach($char as $ch) $nstr .= chr(bindec($ch));
    return $nstr;
}
$bin = binary_encode("String Here");
$str = binary_decode("1010011 1110100 1110010 1101001 1101110 1100111 100000 1001000 1100101 1110010 1100101");
$string="1001"; //this would be 2^0*1+....0...+2^3*1=1+8=9
$bit4=$string[0];//1
$bit3=$string[1];
$bit2=$string[2];
$bit1=$string[3];//1
 0) {
    $bitstring = str_pad($bitstring, intdiv($bitstring_len + 8, 8) * 8, '0', STR_PAD_LEFT);
  }

  $bytestring = '';
  foreach (str_split($bitstring, 32) as $chunk) {
    $bytestring .= pack('H*', str_pad(base_convert($chunk, 2, 16), strlen($chunk) / 4, '0', STR_PAD_LEFT));
  }

  return $bytestring;
}

for ($i = 0; $i < 10000; $i++) {
  $bytestring_in = substr(hash('sha512', uniqid('', true)), 0, rand(0, 128));
  $bits = bytesToBits($bytestring_in);
  $bytestring_out = bitsToBytes($bits);
  if ($bytestring_in !== $bytestring_out) {
    printf("IN  : %s\n", $bytestring_in);
    printf("BITS: %s\n", $bits);
    printf("OUT : %s\n", $bytestring_out);
    var_dump($bytestring_in, $bytestring_out); // printf() doesn't show some characters ..
    die('Error in functions [1].');
  }
}


for ($i = 0; $i < 10000; $i++) {
  $len = rand(0, 128);
  $bitstring_in = '';
  for ($j = 0; $j <= $len; $j++) {
    $bitstring_in .= (string) rand(0,1);
  }
  $bytes = bitsToBytes($bitstring_in);
  $bitstring_out = bytesToBits($bytes);

  // since converting to byte we always have a multitude of 4, so we need to correct the bitstring_in to compare ..
  $bitstring_in_old = $bitstring_in;
  $bitstring_in_len = strlen($bitstring_in);
  if ($bitstring_in_len % 8 > 0) {
    $bitstring_in = str_pad($bitstring_in, intdiv($bitstring_in_len + 8, 8) * 8, '0', STR_PAD_LEFT);
  }

  if ($bitstring_in !== $bitstring_out) {
    printf("IN1  : %s\n", $bitstring_in_old);
    printf("IN2  : %s\n", $bitstring_in);
    printf("BYTES: %s\n", $bytes);
    printf("OUT  : %s\n", $bitstring_out);
    var_dump($bytes); // printf() doesn't show some characters ..
    die('Error in functions [2].');
  }
}

echo 'All ok!' . PHP_EOL;
$bits_in = "101";
$bits_in_len = strlen($bits_in); // <-- keep track if input length
$bits_out = bytesToBits(bitsToBytes("101"));
var_dump($bits_in, $bits_out, substr($bits_out, - $bits_in_len)); // recover original length with substr
var bintext, textresult="", binlength;
    this.aaa = this.text_value;
    bintext = this.aaa.replace(/[^01]/g, "");
        binlength = bintext.length-(bintext.length%8);
        for(var z=0; z

Converting string to binary and binary to string with PHP

-->

Next Lesson PHP Tutorial