Solved

ASPJPEG + ASPUPLOAD.. Using VB!

Posted on 2004-09-12
12
573 Views
Last Modified: 2012-05-05
Hi All,

I have a classic ASP page that uses ASPJPEG and ASPLOAD together .. It uploads the image directly into memory, resizes it, and then inserts it into a MS-SQL Database.

I need code that will do the exact same thing, but using ASP.NET; in VB...  Unfortunately, the persits site has examples that are in C# only.

Can someone paste me their code?  (Upload, resize, insert into MS-SQL) .. in VB!


0
Comment
Question by:tommy10101
  • 7
  • 5
12 Comments
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12039878
The .aspx input control
<TD style="HEIGHT: 34px">Picture <SPAN class="SmallText">(optional)</SPAN></TD>
<TD style="HEIGHT: 34px"><INPUT class="ThinInput" id="ImageSrc" type="file" size="15" runat="server"></TD>
The Code Behind:
Region " AddProduct Button "
    Private Sub AddProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddProduct.Click
        If IsRefresh Then Return

        ProductNameValidator.Enabled = True
        Tier1Validator.Enabled = True
        QueryValidator.Enabled = False
        Validate()

        If Not IsValid Then Return

        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmd As New OleDb.OleDbCommand
        Dim IncomingFile As IO.FileInfo
        Dim ImageSource, PriceValue As String
        Dim ImageResizer As New ResizeImage(True, 300, 400)

        ImageResizer.ThumbX = 100
        ImageResizer.ThumbY = 100

        If ImageSrc.PostedFile.ContentLength <> 0 Then
            IncomingFile = New IO.FileInfo(Request.Files(0).FileName)
            IncomingFile = New IO.FileInfo(Server.MapPath("~/Pictures/Products/") & IncomingFile.Name)
            Request.Files(0).SaveAs(IncomingFile.FullName)
            ImageSource = ImageResizer.ResizeImage(IncomingFile.FullName)
        End If


        If Price.Text = "" Then
            PriceValue = "0"
        Else
            PriceValue = Price.Text
        End If

        cmd.CommandType = CommandType.Text
        cmd.CommandText = "INSERT INTO Products (Tier1ID, Tier2ID, Tier3ID, Name, " & _
            "Description, ImageSrc, Price) VALUES (" & Tier1.SelectedValue & ", " & _
            Tier2.SelectedValue & ", " & Tier3.SelectedValue & ", '" & DBSafe(ProductName.Text) & _
            "', '" & DBSafe(Description.Text) & "', '" & ImageSource & "', " & PriceValue & ")"
        cmd.Connection = cnn

        cnn.Open()
        cmd.ExecuteNonQuery()
        cnn.Close()

        cmd.Dispose()
        cnn.Dispose()

        LoadProductData()
    End Sub
#End Region
Image Resizing Class
Imports System.Drawing
Imports System.Drawing.Imaging

Public Class ResizeImage

    Private _CreateThumbnail As Boolean
    Private _ThumbX, _ThumbY, _FullSizeX, _FullSizeY As Integer
    Private UnacceptableImageFormats As ArrayList

    Public Property CreateThumbnail() As Boolean
        Get
            Return _CreateThumbnail
        End Get
        Set(ByVal Value As Boolean)
            _CreateThumbnail = Value
        End Set
    End Property
    Public Property FullSizeX() As Integer
        Get
            Return _FullSizeX
        End Get
        Set(ByVal Value As Integer)
            _FullSizeX = Value
        End Set
    End Property
    Public Property FullSizeY() As Integer
        Get
            Return _FullSizeY
        End Get
        Set(ByVal Value As Integer)
            _FullSizeY = Value
        End Set
    End Property
    Public Property ThumbX() As Integer
        Get
            Return _ThumbX
        End Get
        Set(ByVal Value As Integer)
            _ThumbX = Value
        End Set
    End Property
    Public Property ThumbY() As Integer
        Get
            Return _ThumbY
        End Get
        Set(ByVal Value As Integer)
            _ThumbY = Value
        End Set
    End Property

    Public Sub New(ByVal CreateThumbnail As Boolean, ByVal FullSizeX As Integer, ByVal FullSizeY As Integer)
        _CreateThumbnail = CreateThumbnail
        _FullSizeX = FullSizeX
        _FullSizeY = FullSizeY

        UnacceptableImageFormats = New ArrayList(10)
        With UnacceptableImageFormats
            .Add(Imaging.PixelFormat.Format1bppIndexed)
            .Add(Imaging.PixelFormat.Format4bppIndexed)
            .Add(Imaging.PixelFormat.Format8bppIndexed)
            .Add(Imaging.PixelFormat.Undefined)
            .Add(Imaging.PixelFormat.DontCare)
            .Add(Imaging.PixelFormat.Format16bppArgb1555)
            .Add(Imaging.PixelFormat.Format16bppGrayScale)
        End With
    End Sub
    Public Function ResizeImage(ByVal ImageSource As String) As String
        Dim IncomingImage As System.Drawing.Image
        Dim OutputBitmap As Bitmap
        Dim JpegCodec As ImageCodecInfo
        Dim JpegEncodeParams As EncoderParameters
        Dim NewSize As Size
        Dim fiSource As New IO.FileInfo(ImageSource)
        Dim fsSource As IO.FileStream
        Dim fiDestination As New IO.FileInfo(ImageSource)
        Dim NewFilename As String

        fiSource.MoveTo(fiSource.DirectoryName & "\TEMP_" & fiSource.Name)
        fsSource = fiSource.OpenRead()
        IncomingImage = IncomingImage.FromStream(fsSource)

        OutputBitmap = RedrawImage(IncomingImage, FullSizeX, FullSizeY)
        If fiSource.Extension = ".gif" Then
            NewFilename = fiDestination.Name
            OutputBitmap.Save(fiDestination.FullName)
        Else
            JpegCodec = ReturnJpegCodec()
            JpegEncodeParams = ReturnEncoderParams()
            NewFilename = fiDestination.Name.Replace(fiDestination.Extension, ".jpg")
            OutputBitmap.Save(fiDestination.FullName.Replace(fiDestination.Extension, ".jpg"), _
                JpegCodec, JpegEncodeParams)
        End If

        If CreateThumbnail Then
            OutputBitmap = RedrawImage(IncomingImage, ThumbX, ThumbY)
            If fiSource.Extension = ".gif" Then
                OutputBitmap.Save(fiDestination.DirectoryName & "/Thumbnails/" & fiDestination.Name)
            Else
                JpegCodec = ReturnJpegCodec()
                JpegEncodeParams = ReturnEncoderParams()
                OutputBitmap.Save(fiDestination.DirectoryName & "/Thumbnails/" & _
                    fiDestination.Name.Replace(fiDestination.Extension, ".jpg"), JpegCodec, JpegEncodeParams)
            End If
        End If

        fsSource.Close()
        OutputBitmap.Dispose()
        IncomingImage.Dispose()
        fiSource.Delete()

        Return NewFilename
    End Function

    Private Function RedrawImage(ByVal IncomingImage As Image, ByVal MaximumX As Integer, _
        ByVal MaximumY As Integer) As Bitmap
        Dim ResizedX, ResizedY As Integer
        Dim Bitmap As Bitmap
        Dim Graphic As Graphics
        Dim NewSize As Size

        ResizedY = CInt((IncomingImage.Height * MaximumX) / IncomingImage.Width)
        ResizedX = CInt((IncomingImage.Width * MaximumY) / IncomingImage.Height)

        If ResizedY >= MaximumY Then
            NewSize = New Size(ResizedX, MaximumY)
        Else
            NewSize = New Size(MaximumX, ResizedY)
        End If

        Bitmap = New Bitmap(IncomingImage, NewSize)
        Bitmap.SetResolution(72, 72)

        'Some graphic pixel formats prevent the image from being converted into an instance of Graphics.
        '   If this is the case, return just the resized bitmap without processing.
        If UnacceptableImageFormats.Contains(Bitmap.PixelFormat) Then Return Bitmap

        'All pixel formats that Microsoft says will generate exceptions have been loaded into the array
        '   above, yet some pixel formats are still throwing exceptions. Resorted to a Try / Catch block - AM
        Try
            Graphic = Graphics.FromImage(Bitmap)
        Catch
            Return Bitmap
        End Try

        Graphic.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        Graphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        Graphic.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality

        Graphic.DrawImage(Bitmap, 0, 0)
        Graphic.Dispose()

        Return Bitmap
    End Function

    Private Function ReturnJpegCodec() As ImageCodecInfo
        Dim codecs As Imaging.ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()

        For Each codec As ImageCodecInfo In codecs
            If codec.MimeType.Equals("image/jpeg") Then Return codec
        Next
    End Function
    Private Function ReturnEncoderParams() As EncoderParameters
        Dim EncoderInstance As Encoder
        Dim EncoderParametersInstance As New EncoderParameters(2)
        Dim QualityParameter As EncoderParameter
        Dim ColorParameter As EncoderParameter

        EncoderInstance = Encoder.Quality
        QualityParameter = New EncoderParameter(EncoderInstance, 80L)
        EncoderParametersInstance.Param(0) = QualityParameter

        EncoderInstance = Encoder.ColorDepth
        ColorParameter = New EncoderParameter(EncoderInstance, 24L)
        EncoderParametersInstance.Param(1) = ColorParameter

        Return EncoderParametersInstance
    End Function

End Class

This example is actually an access db, but just change the providers to the mysql client and your set.  Also this example assumes you only want to keep the path in the db.  I'll post an additional snippit incase you want to store them as blobs in your db.

Regards,

Aeros
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12039881
To upload to blob use this:
<form runat="server" enctype="multipart/form-data" ID="Form2">
  <P>
    <input type="file" id="file1" runat="server" NAME="file1">
  </P>
  <P>
    <asp:Button id="btn1" runat="server" text="Upload" onclick="upload" />
  </P>
</form>

--------------------------------------------------------------------------------------

Imports System.Data
Imports System.Data.SqlClient

Public Sub Upload(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim b(file1.PostedFile.InputStream.Length - 1) As Byte

        file1.PostedFile.InputStream.Read(b, 0, file1.PostedFile.InputStream.Length)

        Dim con As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionStringSQL"))

        Dim sql As String = "INSERT INTO MY_TABLE(MyID, DATABLOB) VALUES(1,@BlobData) "
        Dim cmd As New SqlCommand(sql, con)

        Dim parmBlob As New SqlParameter("@BlobData", SqlDbType.VarBinary, _
                     b.Length, ParameterDirection.Input, False, 0, _
                     0, Nothing, DataRowVersion.Current, b)
                     
        cmd.Parameters.Add(parmBlob)

        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
End Sub
You will need to run in trough the image resizing class I gave you if you need that as well.
0
 

Author Comment

by:tommy10101
ID: 12040166
Hi there Scott!

Sorry for the confusion (my fault).  I actually didn't mean for you to reinvent the wheel by giving me code that is  * equivalent * to Persits ASPJPEG.. What I need * IS * the code to use for Persits ASPJPEG and ASPUPLOAD, in .NET (VB) ..

I'll try your solution also, I appreciate you giving me your code!  Do you have the Persits modules I'm talking about?  Also, is there a website I can test that is using the code above?   Thanks again!

-Tom

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 17

Expert Comment

by:AerosSaga
ID: 12040191
This code is included only in the administrative section of my n-tier applications.  Is there some functionality that your uploading module adds?  I just use my image resizing class, and the built in ASP.NET file upload mechanism works great.  Sorry I misunderstood you, but I really have no experience with the module you mentioned but I think you'll be happy with my code if you try it;) I'm probably a little biased hehe anyway let me know if theres anything else I can do to help you out.

Regards,

Aeros
0
 

Author Comment

by:tommy10101
ID: 12040216
I pasted your code into a page, instead of using it as a code-behind .. I put the script tags around it, and it produces an error ..

<script runat="server">
* your code went here *
</script>
------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30188: Declaration expected.

Source Error:

 

Line 1:  <script runat="server">
Line 2:  Region " AddProduct Button "
Line 3:      Private Sub AddProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddProduct.Click
Line 4:          If IsRefresh Then Return
 ---------------------------------------------------------
.... by the way, what is the #region thing?


0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12040218
thats generated by the ide for the codebehind you would need to take it out, although I highly suggest you develop using the codebehind.
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12040222
This is the only html you neee along with your form tags to create a file upload box:

<TD style="HEIGHT: 34px">Picture <SPAN class="SmallText">(optional)</SPAN></TD>
<TD style="HEIGHT: 34px"><INPUT class="ThinInput" id="ImageSrc" type="file" size="15" runat="server"></TD>
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12040226
Private Sub AddProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddProduct.Click
        If IsRefresh Then Return

        ProductNameValidator.Enabled = True
        Tier1Validator.Enabled = True
        QueryValidator.Enabled = False
        Validate()

        If Not IsValid Then Return

        Dim cnn As New OleDb.OleDbConnection(ConfigurationSettings.AppSettings("SiteDB"))
        Dim cmd As New OleDb.OleDbCommand
        Dim IncomingFile As IO.FileInfo
        Dim ImageSource, PriceValue As String
        Dim ImageResizer As New ResizeImage(True, 300, 400)

        ImageResizer.ThumbX = 100
        ImageResizer.ThumbY = 100

        If ImageSrc.PostedFile.ContentLength <> 0 Then
            IncomingFile = New IO.FileInfo(Request.Files(0).FileName)
            IncomingFile = New IO.FileInfo(Server.MapPath("~/Pictures/Products/") & IncomingFile.Name)
            Request.Files(0).SaveAs(IncomingFile.FullName)
            ImageSource = ImageResizer.ResizeImage(IncomingFile.FullName)
        End If


        If Price.Text = "" Then
            PriceValue = "0"
        Else
            PriceValue = Price.Text
        End If

        cmd.CommandType = CommandType.Text
        cmd.CommandText = "INSERT INTO Products (Tier1ID, Tier2ID, Tier3ID, Name, " & _
            "Description, ImageSrc, Price) VALUES (" & Tier1.SelectedValue & ", " & _
            Tier2.SelectedValue & ", " & Tier3.SelectedValue & ", '" & DBSafe(ProductName.Text) & _
            "', '" & DBSafe(Description.Text) & "', '" & ImageSource & "', " & PriceValue & ")"
        cmd.Connection = cnn

        cnn.Open()
        cmd.ExecuteNonQuery()
        cnn.Close()

        cmd.Dispose()
        cnn.Dispose()

        LoadProductData()
    End Sub

That would be the codebehind, note you would still need to include the image resizing class.  Just go to new then class in visual studio and paste the image resizing class in.  Then you ll need to add that class to your project.
0
 

Author Comment

by:tommy10101
ID: 12040253
Hmm.. I took out the region open and close tags for now .. and it still gives me an error .. I guess I'm stuck here.
0
 

Author Comment

by:tommy10101
ID: 12040258
Just saw your last post .. will try that .. brb
0
 

Author Comment

by:tommy10101
ID: 12040272
Where is the "new" and then "class"?  If I go to "File" and "new", I don't see class as one of the options .. you on AIM by any chance?
0
 
LVL 17

Accepted Solution

by:
AerosSaga earned 350 total points
ID: 12040293
sure let me login handle AerosSaga
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

828 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