Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert image to byte with php

Tags:

php

bytearray

I have to send a picture to a webservice. The web service should receive the image as bytes (mayby bytearray) - not as a string... How do I convert the images to "byte" or bytearray?

I have tried this (without succes):

$image1 = file_get_contents("LINK TO IMAGE");
$image1BinaryData = "".base64_encode($image1)."";

Any help will be appreciated...

like image 200
fletcher Avatar asked May 21 '12 14:05

fletcher


2 Answers

Have you tried to directly read the image as binary data?

<?php
$filename = "image.png";
$file = fopen($filename, "rb");
$contents = fread($file, filesize($filename));
fclose($file);
?>
like image 58
sucotronic Avatar answered Sep 19 '22 11:09

sucotronic


This is the actual byte array equivalent to what is generated in C# and Java.

$data = file_get_contents("test.jpg");

$array = array(); 
foreach(str_split($data) as $char){ 
    array_push($array, ord($char)); 
}
var_dump(implode(' ', $array));
like image 23
Arvind Bhardwaj Avatar answered Sep 22 '22 11:09

Arvind Bhardwaj