简体   繁体   English

PHP 将图像文件转换为二进制字符串

[英]PHP convert Image file to binary string

I want to convert an image I retrieve from a form to binary string so that I can insert it into a sqlplus table.我想将从表单中检索到的图像转换为二进制字符串,以便将其插入到 sqlplus 表中。 I've looked around at how to do this conversion and I found that most solutions have this:我环顾四周如何进行这种转换,我发现大多数解决方案都有这样的:

example table:示例表:

CREATE TABLE images (
    image_id int,
    image blob 
    PRIMARY KEY (image_id));

Form:形式:

<form method="post" enctype="multipart/form-data" action="./Upload/UploadImage.php">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><span style="color: #FF0000;">*</span><br/>
<input type="submit" name="uploadImage" value="Upload Image"></form>

Proposed Conversion Solution:建议的转换解决方案:

<?php
    $data = file_get_contents($_FILES["file"]["tmp_name"]);
    $encoded_data = base64_encode($data);
    //echo the data to check it's there
    echo "Encoded Data: " . $encoded_data;
?>

If I echo $data I get a jumbled string, but if i echo $encoded_data I just get: Encoded Data: then nothing.如果我 echo $data我得到一个混乱的字符串,但如果我 echo $encoded_data我只是得到: Encoded Data:然后什么都没有。

I want to be able to insert this binary data into my db using我希望能够使用这个二进制数据插入到我的数据库中

$sql = 'INSERT INTO images VALUES (1, \'' . $encoded_data . '\')';

(I know this is just the sql string - the execution of the statement is not something I felt I needed to include). (我知道这只是 sql 字符串 - 语句的执行不是我觉得需要包含的内容)。

UPDATE: I realized I had a type in my $encoded_data = base64_encode($data);更新:我意识到我的$encoded_data = base64_encode($data);有一个类型$encoded_data = base64_encode($data); line so that works now but the sql throws a string literal too long error.行,以便现在可以使用,但是 sql 会引发字符串文字太长错误。

$fp = fopen($_FILES['file']['tmp_name'], 'r');
$db_img = fread($fp, filesize($_FILES['file']['tmp_name']));
$db_img = addslashes($db_img);
$db_img = base64_decode($db_img);

then然后

$sql = "INSERT INTO images VALUES (1,'$db_img')"

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

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