Save Image & Create Thumbnail (VB.NET) RRS feed

  • Question

  • User-1661617253 posted
    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> <form runat="server" form-data="form-data" multipart="multipart">

    Upload File

    Browse for Image: <input id="fileUpload1" type="file" size="30" runat="server" />

    <asp:Button id="btnUpload" onclick="btnUpload_Click" runat="server" Text="Upload Image"></asp:Button>
    <asp:Label id="lblMsg" runat="server"></asp:Label> </form>
    Please share with those of us who are C# impaired.
    Friday, November 5, 2004 8:01 PM

All replies

  • User-1025103019 posted
    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.
    Wednesday, January 19, 2005 3:40 PM
  • User-1025103019 posted
    Never mind, I figured out my questions. Thx.
    Wednesday, January 19, 2005 5:10 PM
  • User88235362 posted
    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.
    Saturday, March 5, 2005 8:53 AM
  • User1921716929 posted
    nice code, have code behind version?
    Tuesday, July 19, 2005 5:08 AM
  • User-936122383 posted
    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...
    Friday, July 22, 2005 11:38 AM
  • User-1750044441 posted
    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)
    Dim SqlCommand com = New SqlCommand(conn)
    com.CommandText = String.Format("INSERT INTO images (image_name) VALUES ({0})", imageFilename)
    com = null
    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 ...

    Friday, July 22, 2005 2:20 PM
  • User39490543 posted

    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

    Friday, July 22, 2005 2:52 PM
  • User-1750044441 posted
    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!  ;)


    Friday, July 22, 2005 2:59 PM
  • User-936122383 posted

    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!

    Sunday, July 24, 2005 1:36 PM
  • User-936122383 posted
    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..
    Sunday, July 24, 2005 2:18 PM
  • User-936122383 posted

    Sorry guys [:$], 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..
    Monday, July 25, 2005 3:53 AM
  • User281536433 posted
    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
    Monday, September 12, 2005 6:03 AM
  • User-1130913086 posted
    Does any one know how to determine right rotation for image for automatic handle cases that user uploads up side down picture?   
    Tuesday, September 13, 2005 3:59 AM
  • User-58995815 posted

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

    Thursday, September 15, 2005 12:13 PM
  • User-1810834583 posted

    This image upload free web control supports multiple image definitions (width/height and format) so you can handle up side down picture uploads.


    Monday, November 7, 2005 6:38 AM