0

首先,我想说是的,我确实知道使用文件系统执行此操作并将文件名/位置保存在数据库中是更好的方法,我可能会在最终版本中这样做。

这主要是一个实验/概念证明/学习机会。

我有一个有效的 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)行了,错误参数无效。

有没有更好的方法来读取或写入数据库以使其工作?

4

1 回答 1

0
  • 你为什么要事先对它进行base 64解码?
  • 我建议在上传时保存 memetype,确保解决 ie 的怪异 p-jpeg 问题。

无论如何,这是给你的一堂课。

我的图像.vb

Imports System.Data.SqlClient
Imports System.IO

Public Class MyImage
    Implements IHttpHandler

    Public Function GetImage(ByVal id As Integer, ByVal type As String) As Byte()
        Dim Con As New SqlConnection(Common.ConnectionString)
        Dim cmd As New SqlCommand
        cmd.CommandText = _
            "Select * from tblCompanyImg Where CompanyImgID = @imgID"
        cmd.CommandType = System.Data.CommandType.Text
        cmd.Connection = Con

        cmd.Parameters.AddWithValue("@imgID", id)

        Con.Open()
        Dim dReader As SqlDataReader = cmd.ExecuteReader
        dReader.Read()
        Dim img As Byte()
        If dReader.HasRows Then
            img = dReader("Image")
        Else
            Dim im As New ImageManipulator
            Dim notfound = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Request.PhysicalApplicationPath & "Images\404.jpg")
            img = im.ConvertImageToByteArray(notfound)
        End If

        Con.Close()

        Return img
    End Function

    Function GetMEMEType(ByVal id As Integer) As String
        Dim Con As New SqlConnection(Common.ConnectionString)
        Dim cmd As New SqlCommand
        cmd.CommandText = _
            "Select * from tblCompanyImg Where CompanyImgID = @imgID"
        cmd.CommandType = System.Data.CommandType.Text
        cmd.Connection = Con

        cmd.Parameters.AddWithValue("@imgID", id)

        Con.Open()
        Dim dReader As SqlDataReader = cmd.ExecuteReader
        dReader.Read()
        Dim MEME As String
        If dReader.HasRows Then
            MEME = dReader("MEMEType")
        Else
            MEME = "image/jpeg"
        End If

        Con.Close()

        Return If(MEME = "image/pjpeg", "image/jpeg", MEME)
    End Function

    Public ReadOnly Property IsReusable As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
        Dim path As String = context.Request.Path
        Dim id = path.Split(".")(0).Split("/").Last ' not very pretty, grabs the id from the filename requested
        Dim size = path.Split(".")(1) 'grabs the size required, thumb or full.

        Dim imageData As Byte() = GetImage(id, size)
        context.Response.OutputStream.Write(imageData, 0, imageData.Length)
        'context.Response.
        context.Response.ContentType = GetMEMEType(id)
        'context.Response.AddHeader("content-disposition", "attachment; filename=img.jpg")
    End Sub
End Class

然后将其粘贴到您的 web.config 中

<add verb="GET" path="*.jpg.db" type="project.MyImage,project"  resourceType="Unspecified" name="databaseHandler" />

然后调用 2.jpg.db 将获取您的图像文件。

于 2012-12-12T16:30:48.210 回答