首先,我想说是的,我确实知道使用文件系统执行此操作并将文件名/位置保存在数据库中是更好的方法,我可能会在最终版本中这样做。
这主要是一个实验/概念证明/学习机会。
我有一个有效的 PHP 上传表单。它获取图像并将其转换为 base64 字符串并将其放入数据库表中的图像 blob 中。
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(empty title)';// use (empty title) string
if ($_POST['password'] != $password) // cheking passwors
$msg = 'Error: wrong upload password';
else
{
if (isset($_FILES['photo']))
{
@list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use @ to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if (!isset($msg)) // If there was no error
{
//$file = File Image yang ingin di encode
//Filetype: JPEG,PNG,GIF
$base64 = "";
$file = $_FILES['photo']['tmp_name'];
if($fp = fopen($file,"rb", 0))
{
$gambar = fread($fp,filesize($file));
fclose($fp);
$base64 = chunk_split(base64_encode($gambar));
}
// Preparing data to be used in query
$q = "INSERT INTO tblCompanyImg (CompanyID, ImgNum, ImgExt, ImgName, ImgImg) Values (1, 1, '$ext', '$title', '$base64')";
$database->query($q);
$msg = "Success: image uploaded:";
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
}
}
?>
而且我知道它正在正确保存它,因为我可以像这样查看图像:
<?php
while($row = $database->fetch_array($result))
{
$CompanyImgID = $row["CompanyImgID"];
$CompanyID = $row["CompanyID"];
$ImgName = $row["ImgName"];
// outputing list
echo "<img src='data:image/jpeg;base64," . $row['ImgImg'] . "' />";
}
?>
接下来我想做的是在 Visual Basic 程序中查看上传的图像。
我试过这个:
Dim sSql As String = "Select * from tblCompanyImg Where CompanyImgID = 2"
Dim rSelect As New ADODB.Recordset
Dim img As Image
Dim imageBytes As Byte()
Dim ms As MemoryStream
With rSelect
.Open(sSql, MyCn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockOptimistic)
If Not .EOF Then
imageBytes = .Fields!ImgImg.Value
ms = New MemoryStream(imageBytes, 0, imageBytes.Length)
ms.Write(imageBytes, 0, imageBytes.Length)
img = Image.FromStream(ms, True) ' it fails right here: Parameter is not valid '
LogoPictureBox.Image = img
End If
.Close()
End With
但它失败就img = Image.FromStream(ms, True)
行了,错误参数无效。
有没有更好的方法来读取或写入数据库以使其工作?