繁体   English   中英

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

[英]PHP: Encode image Base64 local

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

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

所以我实际上将文件编码在用户本地计算机上

谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM