Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8976625
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T19:11:27+00:00 2026-06-15T19:11:27+00:00

First off, I want to say that yes, I do know that doing this

  • 0

First off, I want to say that yes, I do know that doing this with file system and just saving the file name/location in the database is the better way to go, and I will probably do that in the final version.

This is mostly an experiment/proof of concept/learning opportunity.

I have a PHP upload form that is working. It takes an image and turns it into a base64 string and puts it into an image blob in the database table.

<?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
    }
}
?>

And I know it is saving it in correctly because I can view the image like this:

<?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'] . "' />"; 
    }
?>

What I would like to do next is to view the uploaded image within a visual basic program.

I tried this:

    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

but it fails on the img = Image.FromStream(ms, True) line with an error Parameter is not valid.

Is there a better way to read or write this to the database to make it work?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T19:11:28+00:00Added an answer on June 15, 2026 at 7:11 pm
    • Why are you base 64 decoding it before hand?
    • I would recommend saving the memetype on upload, making sure to sort out ie’s freaky p-jpeg issues.

    Anyway, here’s a class for you.

    MyImage.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
    

    Then stick this in your web.config

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

    Then calling 2.jpg.db will get your image file.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

so first off, I want to say that this question: Bundle framework with application
First off I want to say that I am not using threads or multiple
First off I want to say that I wasn't really sure where to post
First off, just want to say the Foursquare API is so awesome and tidy!
first i want to say that this site has been a really big help
Just first off I'll say that the context here is Actionscript 3.0 (IDE: Flashbuilder)
First off let me just say, i dont want anyone to post solutions because
First off, let me say that this is not homework (I am an A-Level
First I want to say thanks to everyone that reads this. Stackoverflow is an
First off, I would like to say that I am just starting with PHP

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.