473,595 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Resize image from postef file without saving to disk VB.net?

8 New Member
Hi,
I've just made the change from ASP to .net.
I have a file (code below) that saves a user submitted file to a MS SQL 2005 database. It collects the file name, file size, file type, and lastly the binary data for the file.
I can sucessfully take the files out of the databse again and display them in a data grid.
I would like to resize the submitted file to a fixed size (say 180 x 120) before I upload it to the database and do this without saving it to a temporary file on the servers HDD.
I also do not want to use the "thumbnail method" as I want to keep the quality of the resized smaller images as high as possible.
The code below is stripped down and does not have any validation to check for files that are not images etc, I will add that later. I also don't mind if i can only rezise and store in the database jpeg and gif files, but I need to be able handle at least these two image types.
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1"%>
  2. <%@ Import Namespace="System.IO" %>
  3. <%@ Import Namespace="System.Data" %>
  4. <%@ Import Namespace="System.Data.OleDb" %>
  5. <%@ Import Namespace="System.Configuration" %>
  6. <script language="VB" runat="server">
  7. Public  Sub UploadBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  8.  
  9. 'Get the posted file
  10. Dim fileDataStream As Stream =  MyFile.PostedFile.InputStream 
  11.  
  12. 'get file type
  13. Dim FileType As string = MyFile.PostedFile.ContentType
  14. 'Get size of file
  15. Dim fileLength As Integer =  MyFile.PostedFile.ContentLength 
  16.  
  17. 'Create a byte array with file length
  18. Dim fileData() As Byte =  New Byte(fileLength) {} 
  19.  
  20. 'Read the stream into the byte array
  21. fileDataStream.Read(fileData,0,fileLength)
  22.  
  23. 'get file name (excluding the path)
  24.       Dim strFileNamePath as String = MyFile.PostedFile.FileName
  25.       Dim intFileNameLength = Instr(1, StrReverse(strFileNamePath), "\")
  26.       Dim strFileNameOnly as String = Mid(strFileNamePath, (Len(strFileNamePath)-intFileNameLength)+2)
  27.  
  28.            Dim DBConnection As New OleDbConnection(ConfigurationSettings.AppSettings("MSEMM_Connection_string"))
  29.         Dim UpdateCommand as new oledbcommand
  30.             UpdateCommand.Connection = DBConnection
  31.             UpdateCommand.Commandtype = Commandtype.text 
  32.             UpdateCommand.Commandtext= "INSERT INTO dbo.Files (FileName, FileSize, ContentType, FileData) Values(?,?,?,?)"
  33.             UpdateCommand.Parameters.AddWithValue("?", strFileNameOnly)
  34.             UpdateCommand.Parameters.AddWithValue("?", fileLength)
  35.             UpdateCommand.Parameters.AddWithValue("?", FileType)
  36.             UpdateCommand.Parameters.AddWithValue("?", fileData)
  37.  
  38.         DBConnection.open()
  39.         UpdateCommand.ExecuteNonQuery
  40.         DBConnection.Close()
  41.  
  42. End Sub
  43. </script>
  44. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  45. <html>
  46. <head>
  47. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  48. <title>file upload test</title>
  49. </head>
  50. <body>
  51. <h3>File Upload</h3>
  52.  
  53. <hr>
  54. <asp:label id="Message" Text="Select a file and filename" runat="server"/>
  55. <hr>
  56.  
  57. <h3>File Upload</h3>
  58.  
  59. <form enctype="multipart/form-data" runat="server">
  60.    File: <input id="myFile" type="file" runat="server">
  61.    <input type=button value="Upload" OnServerClick="UploadBtn_Click" runat="server">
  62. </form>
  63. </body>
  64. </html>
  65.  
Mar 1 '08 #1
3 2457
pozze
8 New Member
After some more work I've come up with this, it doesn't come up with an error at run time, and when i check the database there is data in it and the size of the file has decreased, but the image doesn't display, the other images in the database the were uploaded with the original file work fine.
The code of the updated file is below.
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" debug="true"%>
  2. <%@ Import Namespace="System.IO" %>
  3. <%@ Import Namespace="System.Data" %>
  4. <%@ Import Namespace="System.Data.OleDb" %>
  5. <%@ Import Namespace="System.Configuration" %>
  6. <%@ Import Namespace="System.Drawing" %>
  7. <%@ Import Namespace="System.Drawing.Imaging" %>
  8. <%@ Import Namespace="System.Drawing.Drawing2D" %>
  9. <script language="VB" runat="server">
  10. Public  Sub UploadBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  11.  
  12. 'Get the posted file
  13. Dim fileDataStream As Stream =  MyFile.PostedFile.InputStream 
  14.  
  15. 'get file type
  16. Dim FileType As string = MyFile.PostedFile.ContentType
  17. 'Get size of file
  18. Dim fileLength As Integer =  MyFile.PostedFile.ContentLength 
  19.  
  20. 'Create a byte array with file length
  21. Dim fileData() As Byte =  New Byte(fileLength) {} 
  22.  
  23. 'Read the stream into the byte array
  24. fileDataStream.Read(fileData,0,fileLength)
  25.  
  26.  
  27. Dim origImg As System.Drawing.Image
  28.     origImg = System.Drawing.Image.FromStream(fileDataStream)
  29. Dim imageWidth As Integer = origImg.Width
  30. Dim imageHeight As Integer = origImg.Height
  31.  
  32.  
  33. Dim processedBP As Bitmap = New Bitmap (180, 120)
  34. Dim g As Graphics = Graphics.FromImage(processedBP)
  35.     g.SmoothingMode = SmoothingMode.HighQuality
  36.     g.InterpolationMode = InterpolationMode.HighQualityBicubic
  37.     g.PixelOffsetMode = PixelOffsetMode.HighQuality
  38. Dim rect As Rectangle = New Rectangle (0, 0, 180, 120)
  39.     g.DrawImage(origImg, rect, 0, 0, origImg.Width, origImg.Height,GraphicsUnit.Pixel)
  40.  
  41. Dim processedMemStream As MemoryStream = New MemoryStream ()
  42. processedBP.Save(processedMemStream, ImageFormat.Jpeg)
  43. dim FileType2 as string = "image/jpeg"
  44.  
  45. 'Dim processedImageData As Byte = processedMemStream.ToArray()
  46. Dim fileLength2 As Integer = processedMemStream.Length.ToString()
  47. Dim fileData2() As Byte =  New Byte(fileLength2) {}
  48. processedMemStream.Read(fileData2,0,fileLength2)
  49.  
  50. 'get file name (excluding the path)
  51.       Dim strFileNamePath as String = MyFile.PostedFile.FileName
  52.       Dim intFileNameLength = Instr(1, StrReverse(strFileNamePath), "\")
  53.       Dim strFileNameOnly as String = Mid(strFileNamePath, (Len(strFileNamePath)-intFileNameLength)+2)
  54.  
  55.            Dim DBConnection As New OleDbConnection(ConfigurationSettings.AppSettings("MSEMM_Connection_string"))
  56.         Dim UpdateCommand as new oledbcommand
  57.             UpdateCommand.Connection = DBConnection
  58.             UpdateCommand.Commandtype = Commandtype.text 
  59.             UpdateCommand.Commandtext= "INSERT INTO dbo.Files (FileName, FileSize, ContentType, FileData) Values(?,?,?,?)"
  60.             UpdateCommand.Parameters.AddWithValue("?", strFileNameOnly)
  61.             UpdateCommand.Parameters.AddWithValue("?", fileLength2)
  62.             UpdateCommand.Parameters.AddWithValue("?", FileType2)
  63.             UpdateCommand.Parameters.AddWithValue("?", fileData2)
  64.  
  65.         DBConnection.open()
  66.         UpdateCommand.ExecuteNonQuery
  67.         DBConnection.Close()
  68.  
  69. End Sub
  70. </script>
  71. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  72. <html>
  73. <head>
  74. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  75. <title>file upload test</title>
  76. </head>
  77. <body>
  78. <h3>File Upload</h3>
  79.  
  80. <hr>
  81. <asp:label id="Message" Text="Select a file and filename" runat="server"/>
  82. <hr>
  83.  
  84. <h3>File Upload</h3>
  85.  
  86. <form enctype="multipart/form-data" runat="server">
  87.    File: <input id="myFile" type="file" runat="server">
  88.    <input type=button value="Upload" OnServerClick="UploadBtn_Click" runat="server">
  89. </form>
  90. </body>
  91. </html>
  92.  
Mar 1 '08 #2
pozze
8 New Member
Don't worry I've sorted it out myself, I will post the code when i have prettied it up.
Mar 2 '08 #3
kenobewan
4,871 Recognized Expert Specialist
Well done, we gave you the placebo and it worked ;)
Mar 2 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2358
by: Tim T | last post by:
Hi, Could someone please point to to a tutorial / code for dynamically resizing images on upload, THEN saving to disk on the webserver. I need users to be able to upload images to my server, but they will not be aware of optimising graphics for the web, if someone uploads a 300k 640x480 jpeg for example, i need to be able to shrink it down to a - say 400x300 65k file BEFORE saving to my webserver. I have been looking on the web and have...
2
22551
by: Gustavo De la Espriella | last post by:
Hi, I'm having trouble resizing images while mantaining resolution. I used the following code to save a jpeg file to disk, but with the GetThumbImage it loses resolution. ---------------------------------------------- MyImage = System.Drawing.Image.FromFile(Request.PhysicalApplicationPath & "images\TempExterno.jpg") MyImage.GetThumbnailImage(600, (MyImage.Size.Height * (600 / MyImage.Size.Width)), myCallback,...
7
11609
by: lgbjr | last post by:
Hello All, I¡¯m using a context menu associated with some pictureboxes to provide copy/paste functionality. Copying the image to the clipboard was easy. But pasting an image from the clipboard is proving to be more difficult. These pictureboxes are bound to an AccessDB. If the user wants to add an image, they select an image using an OpenFileDialog: Dim result As DialogResult = Pic_Sel.ShowDialog() If (result = DialogResult.OK) Then
15
5322
by: David Lozzi | last post by:
Howdy, I have a function that uploads an image and that works great. I love ..Nets built in upload, so much easier than 3rd party uploaders! Now I am making a public function that will take the path of the uploaded image, and resize it with the provided dimensions. My function is below. The current function is returning an error when run from the upload function: A generic error occurred in GDI+. Not sure what exactly that means. From what...
2
2509
by: Mark Denardo | last post by:
Hi, I need some expert GDI+ person to help me with my RoundOffImage Function: What I'm trying to do is take in an image, crop off the edges around an ellipse region I set up, and then return the cropped image from the function. I sort of have this working, but not thoroughly. If I take the output image of this function and draw it on my form it shows the clipped image as transparent as I am wanting it. But if I take that image and...
4
10235
by: Dale | last post by:
I am creating GIF images with transparent backgrounds on-the-fly for a web app and rendering them by using System.Drawing.Image.Save(Response.OutputStream, ImageType.GIF). I am confident that the transparency is working properly because if I save the created image to the local hard disk and then view it in a web page or an image editor, the transparency is correct. I can also view the transparency on-the-fly in a Windows.Forms...
6
6437
by: Mark Denardo | last post by:
My question is similar to one someone posted a few months back, but I don't see any replies. Basically I want to be able to have users upload photos and save them in a database (as byte data) and be able to load them to an image webcontrol, but system.web.ui.webcontrols.image only seems to have a control to load the image from a URL. There's no way to load this directly without saving the image as a file and then using...
0
1426
by: Waqas.L.Khan | last post by:
Hi guys, I have a problem when trying to create an image file. Basically my code takes any file and gets it's system icon using SHGetFileInfo and then saves the file either by converting it into a bmp and saving to disk or by saving the icon using a filestream. In both cases saving the file works fine. However, when I open the newly created file from explorer I notice something peculiar. The file has a black background. I would have...
3
3187
by: Noorain | last post by:
Sir i want to resize image. Following script working in my local server. But This coding doesn't work in php 2.6.0. please help me <form action="<?php echo $_server; ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm"> <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" /> <button name="submit" type="submit" class="submitButton">Upload/Resize Image</button> </form>...
0
7955
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8251
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6674
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5418
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3873
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3911
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2391
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1490
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.