473,608 Members | 2,565 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Image.FromStrea m - Invalid Parameter Used

Hi

I am storing images in an access database, based on an MSDN article.
The code i use to store is as follows:

<code>

'Create the command object
Dim command As New OleDbCommand("I mageBlobUpdate" , dataConnection)
Command.Command Type = CommandType.Sto redProcedure)

'Get the byte array from the posted file
Dim stream As IO.Stream = sourceFile.Impu tStream ' sourceFile is a
HttpPostedFile object
Dim bytes(Cint(stre am.Length() - 1)) As Byte
stream.Read(byt es, 1, bytes.Length)
stream.Close

'Update the record
command.Paramet ers.Add("id", id)
Dim parameter As New OleDbParameter( "[Image]"),
OleDbType.LongV arBinary, bytes.Length, ParameterDirect ion.Imput,
False, 0, 0, Nothing, DataRowVersion. Current, bytes)
command.Paramet ers.Add(paramet er)
command.Execute NonQuery

</code>

This updates the database fine. I then use the following code to
extract it and convert it to the image:

<code>

'Get a reader containing the image data
Dim command As New OleDbCommand("I mageBlobSelect" , dataConnection)
Command.Command Type = CommandType.Sto redProcedure)
command.Paramet ers.Add("id", id)
Dim reader As OleDbDataReader = command.Execute Reader

'Get the image from the reader
If reader.HasRows Then
reader.Read
Dim bytes(CInt(read er.GetBytes(0, 0, Nothing, 0, Integer.MaxValu e)
- 1)) As Byte
reader.GetBytes (0, 0, bytes, 0, bytes.Length)
Dim stream As New IO.MemoryStream (bytes, 0, bytes.Length)
Dim image As System.Drawing. Image =
System.Drawing. Image.FromStrea m(stream)
End If

'Tidy Up
reader.Close

</code>

When running the code, the error 'Invalid parameter used' is occurs on
the line:

Dim image As System.Drawing. Image =
System.Drawing. Image.FromStrea m(stream)

If i simply write the stream to file, then the file that is created is
the same size as the original image, however it cannot be viewed in
any editor.

The original image is a .JPG.

Any ideas greatly appreciated, I have searched and most solutions
relate to the image header offset, but i do not think this is the
issue.

Cheers

Tom
Nov 21 '05 #1
9 8763
Tom,

Did you already see this sample from me?

http://groups-beta.google.com/group/...9590856?hl=en&

I hope this helps,

Cor
Nov 21 '05 #2
>Did you already see this sample from me?

http://groups-beta.google.com/group/...9590856?hl=en&

Cor

Thanks, yes i have seen your example previously. However, if i
implement your solution to get the image:

<code>

Dim bytes() As Byte = CType(reader.Ge tValue(0), Byte())
Dim stream As New IO.MemoryStream (bytes)
Dim image As Drawing.Image = Drawimg.Image.F romStream(strea m)

</code>

I get the same invalid operator message.

Cheers

Tom
Nov 21 '05 #3
Tom,

Is it the Ole offset problem.

You see one of those (the most normal one) on this page of us.

http://www.windowsformsdatagridhelp....d-253a1ec85fc3

I hope this helps,

Cor
Nov 21 '05 #4
>Is it the Ole offset problem.

You see one of those (the most normal one) on this page of us.

http://www.windowsformsdatagridhelp....d-253a1ec85fc3


Cor

Thanks again. I am at work now, so can't test it until later. However
i did play about with the offset, tried 78 bytes (as per the northwind
example database). However the same problem occured, and when i
attempted to write the image to the filesystem, the resulting file was
78 bytes smaller than the original, therefore i assumed that the
offset could not be causing problems.

I'll look into it further this evening.

Cheers

Tom
Nov 21 '05 #5
Heres routines I wrote to write a byte array to an access database and read
it back. There is no offset needed.

Public Sub WritePicture(Ke yID as Integer, DBConn As OleDb.OleDbConn ection)
'Get Picture from File or whereever into a byte array
Dim fs As FileStream = New System.IO.FileS tream(fname,
IO.FileMode.Ope n, IO.FileAccess.R ead)
Dim byt(CInt(fs.Len gth() - 1)) as Byte
fs.Read(byt, 0, byt.Length)
fs.Close()
'Write Picture to database
Try
DBConn.Open
Dim DBCmd as New OleDb.OleDbComm and("UPDATE ALBUMS SET
FrontCoverPictu re WHERE KeyID = " & Keyid.ToString, DBConn)
Dim P As New OleDb.OleDbPara meter("@FrontCo verPicture",
OleDb.OleDbType .LongVarBinary, Byt.Length, ParameterDirect ion.Input, False,
0, 0, Nothing, DataRowVersion. Current, Byt)
DBCmd.Parameter s.Add(P)
DBCmd.ExecuteNo nQuery()
Catch ex As Exception
'Display Error Message
Finally
DBConn.Close
End Try
End If
End Sub

'Read Image from DataBase
Public Function GetPicture(KeyI d as integer, DBConn as
OleDb.OleDbConn ection ) As Image
Dim Byt as Byte()
Try
DBConn.Open
dim DBCmd as New OleDb.OleDbComm and("SELECT * FROM Albums
WHERE KeyId = " & Keyid.ToString, DBConn)
Dim rdr As OleDb.OleDbData Reader = DBCmd.ExecuteRe ader
While rdr.Read
'Note FrontCoverPictu re is the table name of the picture
column
If Not rdr("FrontCover Picture") Is DBNull.Value Then byt
= CType(rdr("Fron tCoverPicture") , Byte())
End While
Catch ex As Exception
'Display Error Message
Return Nothing
Finally
DBConn.Close
End Try
End If
Return Image.FromStrea m(New IO.MemoryStream (byt))
End Function
--
Dennis in Houston
"Tom John" wrote:
Is it the Ole offset problem.

You see one of those (the most normal one) on this page of us.

http://www.windowsformsdatagridhelp....d-253a1ec85fc3


Cor

Thanks again. I am at work now, so can't test it until later. However
i did play about with the offset, tried 78 bytes (as per the northwind
example database). However the same problem occured, and when i
attempted to write the image to the filesystem, the resulting file was
78 bytes smaller than the original, therefore i assumed that the
offset could not be causing problems.

I'll look into it further this evening.

Cheers

Tom

Nov 21 '05 #6
>
<code>

'Get a reader containing the image data
Dim command As New OleDbCommand("I mageBlobSelect" , dataConnection)
Command.Command Type = CommandType.Sto redProcedure)
command.Paramet ers.Add("id", id)
Dim reader As OleDbDataReader = command.Execute Reader

'Get the image from the reader
If reader.HasRows Then
reader.Read
Dim bytes(CInt(read er.GetBytes(0, 0, Nothing, 0, Integer.MaxValu e)
- 1)) As Byte
reader.GetBytes (0, 0, bytes, 0, bytes.Length)
Dim stream As New IO.MemoryStream (bytes, 0, bytes.Length)
Dim image As System.Drawing. Image =
System.Drawing. Image.FromStrea m(stream)
End If

'Tidy Up
reader.Close

</code>

Instead of reading in the byte array twice (once to define the byte array
size, then once to set the byte array), try the following:

Dim bytes As Byte() = CType(reader.Ge tValue(0), Byte()) ' Just get the
value.

That still doesn't solve your problem though...hmm... lemme try it out and
I'll get back to ya :)

Mythran

Nov 21 '05 #7
I created an MS Access database, with a single table named tblTable. The
table has two columns, id and Image. id is an AutoNumber field and is set
to be the primary key. The Image field is an OLE Object field which will
store the image.

I insert the image into the field using the following method:

Private Shared Sub SaveDetail(ByVa l Connection As OleDbConnection )
Dim command As New OleDbCommand( _
"InsertImageBlo b", _
Connection _
)
Command.Command Type = CommandType.Sto redProcedure

'Get the byte array from the posted file
Dim stream As IO.Stream = IO.File.OpenRea d("C:\lines.bmp ")
Dim bytes As Byte()
ReDim bytes(stream.Le ngth - 1)

stream.Read(byt es, 0, bytes.Length)
stream.Close

' Insert the record.
command.Paramet ers.Add("id", 1)
command.Paramet ers.Add("Image" , bytes)
Common.WriteLn( command.Execute NonQuery & " rows affected.")
End Sub

I then read the image from the database and write it to disk using the
following:

Private Shared Sub ReadDetail(ByVa l Connection As OleDbConnection )
Dim command As New OleDbCommand( _
"ImageBlobSelec t", _
Connection _
)
command.Command Type = CommandType.Sto redProcedure
command.Paramet ers.Add("@Id", 1)

Dim reader As OleDbDataReader = command.Execute Reader()
reader.Read()
Dim bytes As Byte() = CType(reader.Ge tValue(0), Byte())
Dim stream As MemoryStream = New MemoryStream(by tes)
Dim image As Image

' Save the image to disk
Try
image = Image.FromStrea m(stream)
image.Save("C:\ lines_saved.bmp ")
Console.WriteLi ne("Image saved to disk.")
Finally
' Cleanup.
If Not image Is Nothing
image.Dispose()
End If

stream.Close()
End Try
End Sub

Please note, this is not code I would actually use in production. For one,
I would be using another data store (SQL Server most likely). For another,
I would use Microsoft Enterprise Library for my data access layer. Anywho,
that's beside the point. Just posted this as a quick snip for you to try
out and see if it works or not...if it fails, we shall go from there :)

HTH,
Mythran
Nov 21 '05 #8
Ok, Thanks for all your help on this guys. I think i have narrowed
down the problem.

All your examples use a file from the filesystem and open that as a
stream before saving it to the database, when i try this, it works
fine. However i am trying to save an uploaded image, from the
HttpPostedFile object:

Dim stream As System.IO.Strea m = sourceFile.Inpu tStream

This appears not to be working.

Any ideas?

Thanks

Tom
Nov 21 '05 #9

<Tom John> wrote in message
news:7l******** *************** *********@4ax.c om...
Ok, Thanks for all your help on this guys. I think i have narrowed
down the problem.

All your examples use a file from the filesystem and open that as a
stream before saving it to the database, when i try this, it works
fine. However i am trying to save an uploaded image, from the
HttpPostedFile object:

Dim stream As System.IO.Strea m = sourceFile.Inpu tStream

This appears not to be working.

Any ideas?

Thanks

Tom


Imports System.Data.Ole Db
Imports System.IO
Imports System.Drawing

....

Private Sub btnSubmit_Click ( _
ByVal sender As System.Object, _
ByVal e As System.EventArg s _
) Handles btnSubmit.Click
' Save the file to disk.
If Request.Files.C ount > 0
Dim file As HttpPostedFile = Request.Files.G et(0)
Dim conn As OleDbConnection
Dim connString As String = _
"Provider=Micro soft.Jet.OLEDB. 4.0;" & _
"Data Source={0};" & _
"User Id=admin;Passwo rd=;"

connString = String.Format( _
connString, _
Server.MapPath( "~/db2.mdb") _
)

' Open the connection to the database.
conn = New OleDbConnection (connString)
conn.Open()

Try
' Save the file to the database.
SaveFile(conn, file)

' Read the file and save to disk.
ReadFile(conn)
Finally
' Cleanup.
conn.Dispose()
End Try
End If
End Sub

Private Sub SaveFile( _
ByVal Connection As OleDbConnection , _
ByVal PostedFile As HttpPostedFile _
)
Dim command As New OleDbCommand( _
"InsertImageBlo b", _
Connection _
)
Command.Command Type = CommandType.Sto redProcedure

'Get the byte array from the posted file
Dim stream As IO.Stream = PostedFile.Inpu tStream
Dim bytes As Byte()
ReDim bytes(stream.Le ngth - 1)

stream.Read(byt es, 0, bytes.Length)
stream.Close

' Insert the record.
command.Paramet ers.Add("id", 1)
command.Paramet ers.Add("Image" , bytes)
Response.Write( command.Execute NonQuery & " rows affected.<br>")
End Sub

Private Sub ReadFile( _
ByVal Connection As OleDbConnection _
)
Dim command As New OleDbCommand( _
"ImageBlobSelec t", _
Connection _
)
command.Command Type = CommandType.Sto redProcedure
command.Paramet ers.Add("@Id", 1)

Dim reader As OleDbDataReader = command.Execute Reader()
reader.Read()
Dim bytes As Byte() = CType(reader.Ge tValue(0), Byte())
Dim stream As MemoryStream = New MemoryStream(by tes)
Dim image As Image

' Save the image to disk
Try
image = Image.FromStrea m(stream)
image.Save( _
IO.Path.Combine ( _
Server.MapPath( "~/uploads"), _
"uploaded_file. jpg" _
) _
)
Console.WriteLi ne("Image saved to disk.")
Finally
' Cleanup.
If Not image Is Nothing
image.Dispose()
End If

stream.Close()
End Try
End Sub

....

This works file (note, I tested with JPG's). I uploaded a file to the
database using a file upload control (generic), and then fetched it from the
database and saved it to a file.

HTH,
Mythran

Nov 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
3721
by: PS | last post by:
I want to display the image from database to picture box through ado.net and vb.net I have some images present in a sql server 2000 table stored under 'image' datatype. I want to extract and display them in a picture box present in a vb.net form I appreciate any help on this Thanks PS
9
1966
by: Wally | last post by:
I am trying to display images from an Access 2000 database and I get an error "Invalid Parameter Used" when I execute the code line "picBLOB.Image = Image.FromStream(stmBLOBData)" in my Visual Basic .Net application. I have researched MSDN for help and found the example article 321900 (see below) and set up a test and everything works fine when I use SQL Server 2000 but when I modify the code and use data from Access 2000 using an...
1
5141
by: halise irak via .NET 247 | last post by:
I get an "ArgumentException: Invalid parameter used at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement)" exception. it is too ridicilious to get such an exception, can anyone see what might cause that exception? (By the way, i am trying to throw the header part of the image away and extract only
1
2551
by: cs | last post by:
In java I ahve the following code g.drawImage(this.createImage(new MemoryImageSource(r.width, r.height, this.colormap, backstore, r.y*this.width+r.x, this.width)), r.x, r.y, null); where backstore is a byte array (signed) with only zeros In c# I am creating a memory stream, putting the same ammount of signed bytes in it, all with zeros as well, and then doing a System.Drawing.Image.FromStream, but I get a an error:
8
4554
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in XML, and embedded the array as some child element in an xml file, i.e.: <Mask>bHQAAH4AAABCTX4AAAAAAAAAPgAAACgAAAAQAAAAEAAAAAEAAQAAAAAAQAAAAAAAAAAAAA AA AAAAAAAAAAAAAAAA////AP//AAD//wAA//8AAP//AAD/7wAA//cAALtzAABVeQAAVUAAAFVA...
6
3989
by: hb | last post by:
Hi, Would you please give me some idea to convert/decode a Base 64 encoded GIF image string to a *.gif file in ASP.Net? Thank you hb
3
3329
by: harish | last post by:
Hi friends I am facing problem as follow I can't display image from SQL Database to Picture box Control. Here are the codes that I am writing Dim arrPicture() As Byte = _
1
8133
by: Mchuck | last post by:
I've seen several newsgroup topics everywhere concerning this, as well as a couple of articles from the MSDN website, but this error still baffles me. It has to do with using the Image.FromStream(...) function to load an image into a PictureBox control from a byte array received from an SQL Server database. Here's a snippet of what I've been trying to achieve: ----------------------------
12
9250
by: Lance | last post by:
hey all, first time vb.net 2005 user, after sticking vb6 out for a long time... anyway, using this code ====================== Dim FS As FileStream = File.OpenRead(Filename) Dim theImage As Image Try theImage = Image.FromStream(FS, False, False)
0
7998
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8142
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8329
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
6813
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...
1
6010
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5475
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
3959
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
4022
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2472
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

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.