0

I would like for a user to upload an image to a file in my web application. However, before being saved I want to resize the image to a specified size. I have found code on the Internet to do what I want but I am having trouble adapting to meet my needs. Here is the part I am having trouble with:

' Resize Image Before Uploading to DataBase
            Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
            Dim imageHeight As Integer = imageToBeResized.Height
            Dim imageWidth As Integer = imageToBeResized.Width
            Dim maxHeight As Integer = 240
            Dim maxWidth As Integer = 320
            imageHeight = (imageHeight * maxWidth) / imageWidth
            imageWidth = maxWidth

            If imageHeight > maxHeight Then
                imageWidth = (imageWidth * maxHeight) / imageHeight
                imageHeight = maxHeight
            End If

            Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
            Dim stream As System.IO.MemoryStream = New MemoryStream()
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
            stream.Position = 0
            Dim image As Byte() = New Byte(stream.Length) {}
            stream.Read(image, 0, image.Length)

Rather than upload to a database I want to save the image to a folder in my web application. The problem I have encountered is that VB won't let me save a byte() to a folder. Not sure what I can safely change to adapt for my purposes. Why does it need to be changed to a byte() in the first place?

1
  • why don't you just use Bitmap.Save(filename) or use a stream that writes to a file? Commented Oct 6, 2011 at 19:58

2 Answers 2

1

you need to modify here:

 Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
 bitmap.Save("MyFile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

and remove

Dim stream As System.IO.MemoryStream = New MemoryStream()
stream.Position = 0
Dim image As Byte() = New Byte(stream.Length) {}
stream.Read(image, 0, image.Length)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This site is the bomb!
1

If you're not going to save it to the database, then it doesn't need to be changed to a byte(). the shift to BYTE() is used to save it as a SQL BLOB.

Basically, instead of diming a MemoryStream at the end, dim a FileStream, and call the BitMap.Save(stream... on the FileStream.

But remember, that the account that's running ASP.NET/IIS will need write permission on the folder where you're trying to save said file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.