PHP:对图像Base64本地进行编码


PHP: Encode image Base64 local

我想将图像转换为Base64并放入我的数据库中。我知道如何将图像编码到Base64,但我不知道如何使用用户的文件。

因此用户可以使用<input type="file" />"上传"文件但是,在不下载文件并将其存储在服务器上的情况下,我如何处理该文件?

因此,我在用户的计算机上对文件进行了本地编码

感谢

BLOB数据类型最适合存储文件。

  • 这个PHP示例对它做得很好
  • 另请参阅:如何使用PHP将.pdf文件作为BLOB存储到MySQL中
  • MySQL BLOB参考手册有一些有趣的评论

如果您不想将文件保存到数据库,而只是读取它,请使用:

<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>

<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

$content这里有文件内容

要将图像编码到base64,可以使用file_get_contents读取图像文件:

$imageBinaryString = file_get_contents('/image/file/path.png');

http://us1.php.net/file_get_contents

然后base64编码:

$base64_imageString = base64_encode($imageBinaryString);

然后,您可以将其存储在数据库中的text或varchar类型的列中。

<input type="file" name="icon" />

现在尝试使用以下代码。

 $base  =  $_REQUEST['icon'];
 $binary   =  base64_decode($base);
 header('Content-Type: bitmap; charset=utf-8');
 $file  = fopen('upload/imagename.png', 'wb');
 $imagename = 'path_to_image_/images.png';
 fwrite($file, $binary);
 fclose($file);