Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Frustrated over images

Posted on 2010-11-15
Medium Priority
Last Modified: 2012-05-10

I have been attempting to save/retrieve images from an sql server 2005 database off and on for 6 months. I really need help with this.
I have tried numerous examples on the net and have not yet been successfull. I am using Linq to sql to save/retrieve data.
I have a table that stores a before and after picture for each service completed (Services Table).
I also have a table that has a primaryid, foreignkey, foreign key,  two image fields (Before and After),  and a description text field (Portfolio table).
Users have an option to add photos taken during a service to the portfolio table.  The portfolio is visible to the public whereas the service table is only visible to the user.  Users also have the option to add pictures from another souce to the portfolio.
I am having a problem trying to figure out how to make the save and retrieve work when I need to save multiple images.
I have a mangled bunch of code from all my attempts and now am completely lost.
So basically what I am asking, begging, is for a solid example of how I would convert the image in order to save and then convert again in order retrieve and display these images. I using Linq to SQL.  
If you provide a link, the odds are I have read and tried it.

Thanks you

I am building a website that will have a photo album consisting of before/after pictures.  
I also have
Question by:Sheritlw
  • 2
LVL 24

Accepted Solution

alexey_gusev earned 1000 total points
ID: 34143009
Hi, I'm not sure it is what you need, but the following simplified code snippet saves the image (signature captured on mobile device) into sql database (sql ce in this case, but that's irrelevant), and at later stage this image is read from db and sent to server (inserted into mySql db) and shown on web page.
Private Sub menuItemSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuItemSave.Click
            Cursor.Current = Cursors.WaitCursor
            Dim path As String
            path = "My Documents\" & Utils.certId & ".gif"
            Dim bmp As Bitmap = _signature.ScaleImage(220, 120)
            bmp.Save(path, System.Drawing.Imaging.ImageFormat.Gif)
            Dim stream2 As System.IO.FileStream = New System.IO.FileStream(path, IO.FileMode.Open)
            Dim sigLength As Int32 = CInt(stream2.Length)
            Dim img As Byte() = New Byte(stream2.Length) {}
            stream2.Read(img, 0, stream2.Length)
            Dim strsql As String = String.Empty
            If sigLength <> 0 Then
                Dim d, n As String
                d = Utils.certId
                n = ".Gif"
                strsql = "update mytable set " + _
                         "sz='" & img.Length & "'," + _
                         "sig = @Signature where id =" & Utils.Id
                Dim myCommand As New SqlCeCommand(strsql, Utils.sqlCeConnection)
                Dim param As SqlCeParameter = Nothing
                param = New SqlCeParameter("@Signature", Data.SqlDbType.Image)
                myCommand.Parameters("@Signature").Size = img.Length
                myCommand.Parameters("@Signature").Value = img
        Catch ex As Exception
            Utils.LogIt(ex.Message + " " + ex.StackTrace)
            Cursor.Current = Cursors.Default
        End Try
    End Sub

Open in new window

LVL 83

Assisted Solution

CodeCruiser earned 1000 total points
ID: 34143252
This is how I do it in my WinForms app.

The datatype of the field is VarBinary(Max) in SQL Server.
This is the type declaration in class (I manually write my entity classes instead of generating dbml)

<Column(DbType:="Image", UpdateCheck:=UpdateCheck.Never)> _
 Public Property Picture As Image

To read the picture
PictureEdit1.Image = TheEquipment.Picture

To save the picture
TheEquipment.Picture = CreateThumbnail(PictureEdit1.Image, 800, 600)

where CreateThumbnail is a function which returns an Image.

Author Comment

ID: 34152028
Although my code behind is VB, asp.net 3.5 requires additional manipulation of image/binary/byte files.

I have attached the code I have thus far.  

###########CODE BEHIND - FILLING IMAGE CONTROL ###############

    Public Sub FillServices(Optional ByVal iServID As Integer = 0)
        Dim bBefore As Boolean = True
        Dim bPort As Boolean = False
        Using dc As New SalonDataClassesDataContext
            Dim q As Service
            Dim sUserID As String = Session("UserID").ToString
            If iServID > 0 Then
                q = (From a In dc.Services Where a.UserID.ToString = sUserID And a.ServiceID = iServID Select a).FirstOrDefault()
                If q Is Nothing Then
                    'Throw New NullReferenceException("Stylist not found for user ID  " & Session("UserID"))
                    'no record
                    Exit Sub
                End If
                q = (From a In dc.Services Where a.UserID.ToString = sUserID Select a).FirstOrDefault()
                If q Is Nothing Then
                    'Throw New NullReferenceException("Stylist not found for user ID  " & Session("UserID"))
                    'no record
                    Exit Sub
                End If

            End If
            Me.txtClientID.Text = q.ClientID
            Me.txtServiceID.Text = q.ServiceID
            Me.ddPaymentType.SelectedValue = q.PaymentTypeID
            bBefore = True
            Me.imgBeforePhoto.ImageUrl = "~/ImageHandler.ashx?Id=" + q.ServiceID + " bBefore=" + bBefore + " bPort=" + bPort
            bBefore = False
            Me.imgAfterPhoto.ImageUrl = "~/ImageHandler.ashx?Id=" + q.ServiceID + " bBefore=" + bBefore + " bPort=" + bPort
            Me.txtClientEmail.Text = q.Client.emailadd
            Me.txtClientPhone.Text = q.Client.PrimaryPhone
            Me.txtFirstName.Text = q.Client.FName
            Me.txtLastName.Text = q.Client.LName
            Me.txtProductTaxes.Text = q.TotalTaxesProducts.ToString
            Me.txtProductTotal.Text = q.TotalProductPrice.ToString
            Me.txtServiceTaxes.Text = q.TotalServiceTaxes.ToString
            Me.txtServicesTotal.Text = q.TotalServicePrice.ToString
            Me.txtSubTotalServices.Text = q.SubTotalServices.ToString
            Me.txtSubTotalProducts.Text = q.SubTotalProducts.ToString
            Me.txtTip.Text = q.TotalTip.ToString
            Me.txtTaxes.Text = (q.TotalTaxesProducts + q.TotalServiceTaxes).ToString

        End Using

    End Sub

##################### IMAGEHANDLER.ashx ######################

<%@ WebHandler Language="VB" Class="ImageHandler" %>

 Imports System  
 Imports System.Web  
 Imports System.Collections.Generic  
 Imports System.Linq  
 Imports System.IO  
 Imports System.Web.UI  
 Imports System.Web.UI.WebControls  
 Public Class ImageHandler : Implements IHttpHandler  
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim id As String = context.Request.QueryString("Id")
        Dim bBefore As String = context.Request.QueryString("bBefore")
        Dim bPort As String = context.Request.QueryString("bPort")
        context.Response.ContentType = "Image / png"
        'If Not id Is Nothing Then
        Dim strm As Stream = ShowImage(id, bBefore, bPort)

        Dim buffer As Byte() = New Byte(4095) {}
        Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
        While byteSeq > 0
            context.Response.OutputStream.Write(buffer, 0, byteSeq)
            byteSeq = strm.Read(buffer, 0, 4096)
        End While
    End Sub
    Public Function ShowImage(ByVal id As String, ByVal bBefore As String, ByVal bPort As String) As Stream
        Dim dc As New SalonDataClassesDataContext
        If bPort = "True" Then
            Dim g As New Guid(id)
            Dim r = (From a In dc.Portfolios _
                     Where a.UserID = g).FirstOrDefault()
            If bBefore = "True" Then
                Return New MemoryStream(r.BeforePic.ToArray())
            ElseIf bBefore Is Nothing Then
                Return Nothing
                Return New MemoryStream(r.AfterPic.ToArray())
            End If
        Else 'select from service
            Dim r = (From a In dc.Services _
                     Where a.ServiceID = id).FirstOrDefault()
            If bBefore = "True" Then
                Return New MemoryStream(r.BeforePic.ToArray())
            ElseIf bBefore Is Nothing Then
                Return Nothing
                Return New MemoryStream(r.AfterPic.ToArray())
            End If
        End If
    End Function
     Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable  
             Return False  
         End Get  
     End Property  
 End Class  

################## SAVE IMAGE FILES ####################

    Private Sub SaveService()
        Dim dc As New SalonDataClassesDataContext
        Dim u As New SalonUtilities
        Dim sUserID As String = u.CheckSessionAndReturnUser
        Dim g As New Guid(sUserID)
        Dim iService As Int32 = 0
        Dim iClientID As Int32 = 0
        If IsNumeric(Me.txtServiceID.Text) Then
            iService = Int32.Parse(Me.txtServiceID.Text)
        End If
        If IsNumeric(Me.txtClientID.Text) Then
            iClientID = Int32.Parse(Me.txtClientID.Text)
        End If

        Dim fbBefore As Byte() = Me.fuBeforePhoto.FileBytes
        Dim fbAfter As Byte() = Me.fuAfterPhoto.FileBytes
        Dim fbinBefore As New System.Data.Linq.Binary(fbBefore)
        Dim fbinAfter As New System.Data.Linq.Binary(fbAfter)
        Dim dSubServ As Decimal = 0
        Dim dTotalServ As Decimal = 0
        Dim dServTax As Decimal = 0
        Dim dSubProd As Decimal = 0
        Dim dTotalProd As Decimal = 0
        Dim dProdTax As Decimal = 0
        Dim dTip As Decimal = 0
        Dim iRecID As Integer = 0

        If IsNumeric(Me.txtSubTotalProducts.Text) Then
            dSubProd = Decimal.Parse(Me.txtSubTotalProducts.Text)
        End If
        If IsNumeric(Me.txtSubTotalServices.Text) Then
            dSubServ = Decimal.Parse(Me.txtSubTotalServices.Text)
        End If
        If IsNumeric(Me.txtProductTotal.Text) Then
            dTotalProd = Decimal.Parse(Me.txtProductTotal.Text)
        End If
        If IsNumeric(Me.txtServicesTotal.Text) Then
            dTotalServ = Decimal.Parse(Me.txtServicesTotal.Text)
        End If
        If IsNumeric(Me.txtServiceTaxes.Text) Then
            dServTax = Decimal.Parse(Me.txtServiceTaxes.Text)
        End If
        If IsNumeric(Me.txtProductTaxes.Text) Then
            dProdTax = Decimal.Parse(Me.txtProductTaxes.Text)
        End If

        If IsNumeric(Me.txtTip.Text) Then
            dTip = Decimal.Parse(Me.txtTip.Text)
        End If

        Dim s = dc.stp_Service_Insert_Update(iService, g, iClientID, Me.ddPaymentType.SelectedItem.Value, _
           fbinBefore, fbinAfter, Me.txtDetailsDescribe.Text, dSubServ, dTotalServ, dServTax, _
            dSubProd, dTotalProd, dProdTax, dTip, iRecID)

        Me.txtServiceID.Text = iRecID

Open in new window

LVL 83

Expert Comment

ID: 34153467
Is the problem with the ASP.NET side or the LINQ? Is the image being saved and retrieved correctly? Where is the class code?

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
The Relationships Diagram is a good way to get an overall view of what a database is keeping track of. It is also where relationships are defined. A relationship specifies how two tables connect to each other. As you build tables in Microsoft Ac…
Suggested Courses

572 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question