PHP 将图像转换为二进制文件测试


PHP converting an image to a binary file test

我想尝试将图像转换为二进制。

我在网上找到了一个脚本,但它不起作用。

有人可以告诉为什么吗?

<?php
$image="image003.jpg";
$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($fd, $size);
fclose ($fd);
$encoded= base64_encode($contents);
echo $encoded;
 ?>

我在第 8 行和第 9 行出现错误

Warning: fread() expects parameter 1 to be resource

Warning: fclose() expects parameter 1 to be resource,

使用 $data 而不是 $fd

$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($data, $size);
fclose ($data);

正如你在这里看到的 http://php.net/manual/en/function.fread.php。
因此,正如您可以阅读fread需要一个资源生成 fopen .

在您的情况下:

<?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;
?>