简体   繁体   English

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

[英]PHP: Encode image Base64 local

I want to convert a image to Base64 and put in into my database. 我想将图像转换为Base64并放入数据库中。 I know how to encode a image to Base64, but I dont know how to use a file from a user. 我知道如何将图像编码为Base64,但我不知道如何使用用户的文件。

So the user can "upload" a file with <input type="file" /> But how can I approach that file without download the file and store it at my server? 因此,用户可以使用<input type="file" /> “上传”文件,但是如何在不下载文件并将其存储在服务器上的情况下处理该文件呢?

So i encode the file actually localy on the user his/her computer 所以我实际上将文件编码在用户本地计算机上

Thanks 谢谢

The BLOB datatype is best for storing files. BLOB数据类型最适合存储文件。

if you do not want to save the file to the database, but just read it, use: 如果您不想将文件保存到数据库,而只是阅读它,请使用:

<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 here has the file content $ content这里有文件内容

To encode an image to base64 you can use file_get_contents to read the image file: 要将图像编码为base64,可以使用file_get_contents读取图像文件:

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

http://us1.php.net/file_get_contents http://us1.php.net/file_get_contents

Then base64 encode: 然后base64编码:

$base64_imageString = base64_encode($imageBinaryString);

You can then store in database in a column with type text or varchar. 然后,您可以将数据库存储在类型为text或varchar的列中。

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

Now try with below code. 现在尝试下面的代码。

 $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