Save Image & Create Thumbnail (VB.NET)

Last post 11-07-2005 6:38 AM by zioturo. 15 replies.

Sort Posts:

  • Save Image & Create Thumbnail (VB.NET)

    11-05-2004, 8:01 PM
    • Member
      30 point Member
    • Shadam
    • Member since 01-13-2004, 8:32 PM
    • St. John's, NL, Canada
    • Posts 6
    I know that lots of people (including myself) have been searching all over for a working copy of a page that uploads a JPEG image and creates a thumbnail to go along with it. I have found lots of these pages written in C#, but I am an old geezer when it comes to programming and I wanted to do it in VB.

    Here is an entire VB upload and resize file for anyone to use. It uploads one JPEG file to a directory off the server's root and creates a Thumbnail that is 300 pixels wide in the same folder. It has limited error catching, only the basic code to get you started.


    <%@ Page Language="VB" Debug="true" %>
    <%@ import Namespace="System.IO" %>
    <%@ import Namespace="System.Drawing.Imaging" %>
    <%@ import Namespace="System.Drawing" %>
    <script runat="server">

    Dim uploadSucess As Boolean
    Dim strFileName As String
    Dim filepath as String
    Sub btnUpload_Click(sender As Object, e As EventArgs)

    uploadSucess = uploadMainImage()
    If (uploadSucess) Then
    generateThumbnail()
    End If
    End Sub

    Function UploadMainImage()
    'Check to make sure we actually have a file to upload
    If Not (fileupload1.PostedFile Is Nothing) Then
    Dim strLongFilePath As String = fileupload1.PostedFile.FileName
    Dim intFileNameLength As Integer = InStr(1, StrReverse(strLongFilePath), "\")
    strFileName = Mid(strLongFilePath, (Len(strLongFilePath) - intFileNameLength) + 2)

    Select Case fileupload1.PostedFile.ContentType
    'Make sure we are getting a valid JPG image
    Case "image/pjpeg", "image/jpeg"
    filepath = Server.MapPath("\") & "\uploaded_images\"
    fileupload1.PostedFile.SaveAs(filepath & strFileName)
    Return True
    Case Else
    'Not a valid jpeg image
    lblMsg.Text = "Not a valid jpeg image"
    Return False
    End Select
    End If
    End Function

    Function generateThumbnail()
    'Create a new Bitmap Image loading from location of origional file
    Dim bm as Bitmap = System.Drawing.Image.FromFile(filePath & strFileName)

    'Declare Thumbnails Height and Width
    Dim newWidth as Integer = 300
    Dim newHeight as Integer = (newWidth/bm.width)*bm.Height

    'Create the new image as a blank bitmap
    Dim resized as Bitmap = new Bitmap(newWidth,newHeight)

    'Create a new graphics object with the contents of the origional image
    Dim g as Graphics = Graphics.FromImage(resized)

    'Resize graphics object to fit onto the resized image
    g.DrawImage(bm, new Rectangle(0,0,resized.Width,resized.Height),0,0,bm.Width,bm.Height,GraphicsUnit.Pixel)

    'Get rid of the evidence
    g.Dispose()

    'Create new path and filename for the resized image
    Dim newStrFileName as String = FilePath & "T_" & strFileName

    'Save the new image to the same folder as the origional
    resized.Save(newStrFileName,ImageFormat.Jpeg)

    End Function

    </script>
    <html>
    <head>
    </head>
    <body>
    <form runat="server" form-data="form-data" multipart="multipart">
    <table width="500">
    <tbody>
    <tr>
    <td colspan="2">
    <p class="NormalBold" align="center">
    Upload File
    </p>
    </td>
    </tr>
    <tr>
    <td>
    Browse for Image:</td>
    <td>
    <input id="fileUpload1" type="file" size="30" runat="server" /></td>
    </tr>
    <tr>
    <td>
    <p>
    </p>
    </td>
    <td>
    <asp:Button id="btnUpload" onclick="btnUpload_Click" runat="server" Text="Upload Image"></asp:Button>
    </td>
    </tr>
    </tbody>
    </table>
    <asp:Label id="lblMsg" runat="server"></asp:Label>
    </form>
    </body>
    </html>



    Please share with those of us who are C# impaired.
    Shadam
    www.shadam.com

    Just because I'm wrong doesn't mean I'm not right.
  • Re: Save Image & Create Thumbnail (VB.NET)

    01-19-2005, 3:40 PM
    • Contributor
      2,021 point Contributor
    • vljw8202
    • Member since 09-29-2004, 2:54 PM
    • Toronto
    • Posts 422
    This is great. Correct me from wrong, all of these codes are within the aspx file and nothing in aspx.vb. I copied and parsed them into aspx and aspx.vb files but I got "ImageFormat" (last line in GenerateThumbnail function) not declared. I commented this line out and ran it. I was able to upload the image file. Did I do something wrong or miss anything and caused the "not declared" error? Anyway thank you for sharing codes with others.
  • Re: Save Image & Create Thumbnail (VB.NET)

    01-19-2005, 5:10 PM
    • Contributor
      2,021 point Contributor
    • vljw8202
    • Member since 09-29-2004, 2:54 PM
    • Toronto
    • Posts 422
    Never mind, I figured out my questions. Thx.
  • Re: Save Image & Create Thumbnail (VB.NET)

    03-05-2005, 8:53 AM
    • Participant
      883 point Participant
    • gavinharriss
    • Member since 03-05-2005, 8:07 AM
    • Posts 302
    If you want some ready made code to automatically generate the thumbnail images for you the code associated with the article http://www.codeproject.com/useritems/colorwash.asp has some bonus functionality to do this for you via the "ImposeUpperLimitOnDimensions" method of the GavDev.Image.Manipulate class library.

    The article itself is aimed at applying a color wash to images, but the bonus functionality is mentioned very breifly at the bottom of the article and works very well.

    Simple download the code associated with the article and drop GavDev.Image.dll into your bin directory then make a reference to it in your project to start using the functionality.
    Gavin Harriss
    Portfolio: www.gavinharriss.com
  • Re: Save Image & Create Thumbnail (VB.NET)

    07-19-2005, 5:08 AM
    • Member
      277 point Member
    • Afgdef
    • Member since 07-09-2004, 3:41 PM
    • Posts 62
    nice code, have code behind version?
  • problems with ur code

    07-22-2005, 11:38 AM
    • Member
      50 point Member
    • deulu
    • Member since 07-22-2005, 3:30 PM
    • Posts 10
    hi..
    i'm not any professional in vb.net..i used ur code but an error keeps occuring:
    Could not find a part of the path "c:\inetpub\wwwroot\test.aspx\images\Image(154).jpg"
     
    i know there's something going wrong in setting this line correct : filepath = Server.MapPath("\") & "\uploaded_images\"
    i know it might sound silly to you especially the other guys had ur script work out nicely...
    i can't figure out how to define the server.mappath
    i would appreciate any kind of help, i need it really urgently...
    Another question if possible, if i need to connect to the sql database and save the name of my image in a table called images, how can i do it?

    thanks for any help u can provide...
  • Re: problems with ur code

    07-22-2005, 2:20 PM
    • Member
      90 point Member
    • jethompson
    • Member since 07-14-2005, 9:17 PM
    • Posts 18
    You'll need to figure out the best way to get your path from the web server.

    In the line that grabs the filepath, the Server.MapPath("\") is grabbing the root of your web server in IIS.  Generally, this will be "C:\Inetpub\wwwroot\".

    If you are using virtual directories, you'll want to map the path to the virtual directory name.  You can just hard code this into your MapPath query (Server.MapPath("virtual directory name")) or grab it from IIS to make it dynamic (Server.MapPath(Request.ApplicationPath)).  This will then give you "C:\Inetpub\wwwroot\virtual directory name\".

    Now, the last bit on the MapPath call above is just appending the image foldername, uploaded_images.  It's pretty much saying take the base IIS folder and add the images folder to it, so we'll end up with filepath = "C:\Inetpub\wwwroot" & "\uploaded_images\" which will result in "C:\Inetput\wwwroot\uploaded_images\".

    If you are using a virtual, you'll need to adjust your MapPath to use that.  Also, if you're using a different folder name, update the portion that appends the images folder name to the folder name you are using.

    If you plan on saving the thumbnails back to the images folder, you'll need to ensure that the ASPNET user account (Network Service on Windows 2003) has write permissions to that folder.

    Regarding saving the filenames to a table called images, after you have the final filename you want to save to SQL Server, just use something along the following (you'll need to reference the System.Data.SqlClient namespace):

    Dim String connectionString = "connection string value"
    Dim SqlConnection conn = New SqlConnection(connectionString)
    conn.Open()
    Dim SqlCommand com = New SqlCommand(conn)
    com.CommandText = String.Format("INSERT INTO images (image_name) VALUES ({0})", imageFilename)
    com.ExecuteNonQuery()
    com = null
    conn.Close()
    conn = null

    Something like that should work.  Obviously, you won't want to hard-code your connection string value into your web page or code.  Also, you'll probably want to use a stored procedure instead of an SQL string in your code.

    I'm not sure if the code will actually work, either.  I just spit it out off the top of my head, and I haven't coded in VB since VB6 ...

  • Re: problems with ur code

    07-22-2005, 2:52 PM
    • All-Star
      42,326 point All-Star
    • tmorton
    • Member since 08-06-2002, 9:37 PM
    • SE Pennsylvania, USA
    • Posts 7,032
    • ASPInsiders
      Moderator
     jethompson wrote:

    Also, you'll probably want to use a stored procedure instead of an SQL string in your code.


    At the very least you should use a Parameter, and not String.Format which is very insecure and opens you up to the possibility of SQL Injection.  Something like this would be better:

    com.CommandText = "INSERT INTO images (image_name) VALUES (@Filename)"
    com.Parameters.Add(New SqlParameter("@Filename", SqlDbType.VarChar,50)).Value = imageFilename

    Terri Morton
    ASP.NET Website Manager, Neudesic
  • Re: problems with ur code

    07-22-2005, 2:59 PM
    • Member
      90 point Member
    • jethompson
    • Member since 07-14-2005, 9:17 PM
    • Posts 18
    Excellent point.  I'm so used to using my data access layer and stored procedures or functions that I totally forgot about that.

    In the real world, you shouldn't be using raw SQL anyway.  Also, don't use dynamic SQL inside your stored procedure, as SQL injection attacks can be carried out there, as well!

    Thanks for catching that!  ;)

    Jason

  • Re: problems with ur code

    07-24-2005, 1:36 PM
    • Member
      50 point Member
    • deulu
    • Member since 07-22-2005, 3:30 PM
    • Posts 10

    hi jason..
    Thanks alot for the help! It worked perfectly well....
    but something about saving the image in the database... i did the following:

    Dim strConn As String = "server=HELPDESK-04;uid=sa;pwd=**secret**;database=NaharDB"

    Dim commandText As String = "INSERT INTO images (image_title) VALUES (@Filename)"

    Dim MyConn As SqlConnection = New SqlConnection(strConn)

    Dim Cmd As SqlCommand = New SqlCommand(commandText, MyConn)

    Cmd.Parameters.Add(New SqlParameter("@Filename", SqlDbType.VarChar, 50)).Value =strfilename



    What's wrong in this code, cus it keeps displaying in my database <binary> instead of the name of the image..i made sure that the type of the image_title is image.
    What should be instead of ImageFilename, shouldn't it be strfilename?

    i'm really sorry guys for the disturbance, but it's really important for me to figure it out...
    I really appreciate your help...

    Edited by moderator tmorton - do not show login credentials in your connection string!

  • Re: problems with ur code

    07-24-2005, 2:18 PM
    • Member
      50 point Member
    • deulu
    • Member since 07-22-2005, 3:30 PM
    • Posts 10
    I drop my previous question...i was really stupied..i should have given a type of varchar to the "image_title" and not type image...
    so sorry guys..
    It all worked out perfectly well...
    thanks alot..
  • Re: Save Image & Create Thumbnail (VB.NET)

    07-25-2005, 3:53 AM
    • Member
      50 point Member
    • deulu
    • Member since 07-22-2005, 3:30 PM
    • Posts 10

    Sorry guys Embarrassed [:$], but I've got two more question concerning creating thumbnails..
    If i need to display the saved resizable image(small image) in my page immediately after saving it to the database without using datagrid or datalist, can i do that and how?

    and the second question is that, i've done the following in my body:
    <img src='images/<%#DataBinder.Eval(Container.DataItem,"ImagePath")%>' border="0" vspace="10" onclick="window.open('file.html','myWin','width=300,height=300,top=100,left=100,toolbar=0,menubar=0,location=0,status=0,scrollbars=1,resizable=1')" id=IMG1>
    so that when i click on this same image, it will generate a small popup window (file.html)...but the first thing that is happening is that it is displaying to me the following compilation error:
     BC30456: 'DataItem' is not a member of 'System.Web.UI.Control'.

    I've read lots of codes concerning clicking on an image to popup the real size of the pic but non of them worked fine..
    Does anyone have a clue of how to do this?

    Thanks so..
                                                    
  • Re: Save Image & Create Thumbnail (VB.NET)

    09-12-2005, 6:03 AM
    • Member
      15 point Member
    • jsmythe
    • Member since 08-25-2005, 10:21 AM
    • Posts 3
    hi sorry if i am bringing this thread alive again but i have just found this code and it came in very useful for some work i am doing. I have one question tho what would i do to delete the file from the server? Basically i am allowing users to upload artwork onto a website to create a virtual art gallery, i have already added code so that as each file is created there is a record added to a database for the location of the file, and i can also delete the record out of the database but now i just need to figure out how to delete the physical file off the server!
    Any help will be much appreciated
  • Re: Save Image & Create Thumbnail (VB.NET)

    09-13-2005, 3:59 AM
    • Member
      307 point Member
    • Skiff
    • Member since 03-03-2003, 2:49 PM
    • Posts 79
    Does any one know how to determine right rotation for image for automatic handle cases that user uploads up side down picture?   
  • Re: Save Image & Create Thumbnail (VB.NET)

    09-15-2005, 12:13 PM
    • Member
      50 point Member
    • oceanfeeling
    • Member since 05-23-2005, 1:45 PM
    • Posts 11

    First, you have to grab the path to the original file, your users upload.
    Let's say that "image0.jpg" is the uploaded file and "image1.jpg" and "image1_thumb.jpg" are the files you create with your code.

    Dim path As String = Server.MapPath("/directoryname/images/" & uploadedfile)
    Dim objFile As File
    Try
       objFile.Delete(path)
    Catch ex As Exception
       Response. Write(ex.Message.ToString)
    End Try

    uploadedfile is a variable for holding the original name of the picture your users upload to the server

Page 1 of 2 (16 items) 1 2 Next >