Solved

Frustrated over images

Posted on 2010-11-15
4
458 Views
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
0
Comment
Question by:Sheritlw
  • 2
4 Comments
 
LVL 24

Accepted Solution

by:
alexey_gusev earned 250 total points
Comment Utility
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

        Try

            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)

            stream2.Close()

 

            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.Add(param)

                myCommand.Parameters("@Signature").Size = img.Length

                myCommand.Parameters("@Signature").Value = img

                myCommand.ExecuteNonQuery()

 

                File.Delete(path)

 

        Catch ex As Exception

            Utils.LogIt(ex.Message + " " + ex.StackTrace)

        Finally

            Cursor.Current = Cursors.Default

        End Try

    End Sub

Open in new window

0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 250 total points
Comment Utility
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.
0
 

Author Comment

by:Sheritlw
Comment Utility
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.  

Thanks
###########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

            Else

                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

            Else

                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

            Else

                Return New MemoryStream(r.AfterPic.ToArray())

            End If

            

        End If

        

        

        

    End Function

    

    

    

     Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable  

         Get  

             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

0
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
Is the problem with the ASP.NET side or the LINQ? Is the image being saved and retrieved correctly? Where is the class code?
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now