PHP / Codeigniter - How to convert image to byte array? [closed]

0

I want to leave here registered my solution to this problem.

$data = file_get_contents("/ImagePath/Image.jpg");

$array = array(); 

foreach(str_split($data) as $char){ 
   array_push($array, ord($char)); 
}
    
asked by anonymous 24.06.2015 / 16:35

2 answers

2

Tried to read the direct image as binary data?

<?php
$filename = "image.png";
$file = fopen($filename, "rb");
$contents = fread($file, filesize($filename));
fclose($file);
?>

If you are submitting via form, convert $contents to base64 using base64_encode($contents) .

    
24.06.2015 / 16:42
1

@FelipeDouradinho's answer was cool. But if you want to create an array of bytes, you would have to do so.

    $filename = "image.png";

    $file = fopen($filename, "rb");

    $tamanho_do_buffer = 4096;

    $array = array();

    while (! feof($file)) {

        $array[] = fread($file, $tamanho_do_buffer);
    }

    fclose($file);

Using file_get_contents in this case is not recommended. file_get_contents returns the entire contents of the file. The fopen combined with the fread defines a specific size of the buffer face that will be opened from the file, thus avoiding an overhead in memory (depending on your script may generate an error if the memory usage reaches the limit defined in PHP)

    
24.06.2015 / 17:24