473,406 Members | 2,378 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Image.FromStream - 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("ImageBlobUpdate", dataConnection)
Command.CommandType = CommandType.StoredProcedure)

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

'Update the record
command.Parameters.Add("id", id)
Dim parameter As New OleDbParameter("[Image]"),
OleDbType.LongVarBinary, bytes.Length, ParameterDirection.Imput,
False, 0, 0, Nothing, DataRowVersion.Current, bytes)
command.Parameters.Add(parameter)
command.ExecuteNonQuery

</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("ImageBlobSelect", dataConnection)
Command.CommandType = CommandType.StoredProcedure)
command.Parameters.Add("id", id)
Dim reader As OleDbDataReader = command.ExecuteReader

'Get the image from the reader
If reader.HasRows Then
reader.Read
Dim bytes(CInt(reader.GetBytes(0, 0, Nothing, 0, Integer.MaxValue)
- 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.FromStream(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.FromStream(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 8735
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.GetValue(0), Byte())
Dim stream As New IO.MemoryStream(bytes)
Dim image As Drawing.Image = Drawimg.Image.FromStream(stream)

</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(KeyID as Integer, DBConn As OleDb.OleDbConnection)
'Get Picture from File or whereever into a byte array
Dim fs As FileStream = New System.IO.FileStream(fname,
IO.FileMode.Open, IO.FileAccess.Read)
Dim byt(CInt(fs.Length() - 1)) as Byte
fs.Read(byt, 0, byt.Length)
fs.Close()
'Write Picture to database
Try
DBConn.Open
Dim DBCmd as New OleDb.OleDbCommand("UPDATE ALBUMS SET
FrontCoverPicture WHERE KeyID = " & Keyid.ToString, DBConn)
Dim P As New OleDb.OleDbParameter("@FrontCoverPicture",
OleDb.OleDbType.LongVarBinary, Byt.Length, ParameterDirection.Input, False,
0, 0, Nothing, DataRowVersion.Current, Byt)
DBCmd.Parameters.Add(P)
DBCmd.ExecuteNonQuery()
Catch ex As Exception
'Display Error Message
Finally
DBConn.Close
End Try
End If
End Sub

'Read Image from DataBase
Public Function GetPicture(KeyId as integer, DBConn as
OleDb.OleDbConnection ) As Image
Dim Byt as Byte()
Try
DBConn.Open
dim DBCmd as New OleDb.OleDbCommand("SELECT * FROM Albums
WHERE KeyId = " & Keyid.ToString, DBConn)
Dim rdr As OleDb.OleDbDataReader = DBCmd.ExecuteReader
While rdr.Read
'Note FrontCoverPicture is the table name of the picture
column
If Not rdr("FrontCoverPicture") Is DBNull.Value Then byt
= CType(rdr("FrontCoverPicture"), Byte())
End While
Catch ex As Exception
'Display Error Message
Return Nothing
Finally
DBConn.Close
End Try
End If
Return Image.FromStream(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("ImageBlobSelect", dataConnection)
Command.CommandType = CommandType.StoredProcedure)
command.Parameters.Add("id", id)
Dim reader As OleDbDataReader = command.ExecuteReader

'Get the image from the reader
If reader.HasRows Then
reader.Read
Dim bytes(CInt(reader.GetBytes(0, 0, Nothing, 0, Integer.MaxValue)
- 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.FromStream(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.GetValue(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(ByVal Connection As OleDbConnection)
Dim command As New OleDbCommand( _
"InsertImageBlob", _
Connection _
)
Command.CommandType = CommandType.StoredProcedure

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

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

' Insert the record.
command.Parameters.Add("id", 1)
command.Parameters.Add("Image", bytes)
Common.WriteLn(command.ExecuteNonQuery & " rows affected.")
End Sub

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

Private Shared Sub ReadDetail(ByVal Connection As OleDbConnection)
Dim command As New OleDbCommand( _
"ImageBlobSelect", _
Connection _
)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@Id", 1)

Dim reader As OleDbDataReader = command.ExecuteReader()
reader.Read()
Dim bytes As Byte() = CType(reader.GetValue(0), Byte())
Dim stream As MemoryStream = New MemoryStream(bytes)
Dim image As Image

' Save the image to disk
Try
image = Image.FromStream(stream)
image.Save("C:\lines_saved.bmp")
Console.WriteLine("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.Stream = sourceFile.InputStream

This appears not to be working.

Any ideas?

Thanks

Tom
Nov 21 '05 #9

<Tom John> wrote in message
news:7l********************************@4ax.com...
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.Stream = sourceFile.InputStream

This appears not to be working.

Any ideas?

Thanks

Tom


Imports System.Data.OleDb
Imports System.IO
Imports System.Drawing

....

Private Sub btnSubmit_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles btnSubmit.Click
' Save the file to disk.
If Request.Files.Count > 0
Dim file As HttpPostedFile = Request.Files.Get(0)
Dim conn As OleDbConnection
Dim connString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source={0};" & _
"User Id=admin;Password=;"

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( _
"InsertImageBlob", _
Connection _
)
Command.CommandType = CommandType.StoredProcedure

'Get the byte array from the posted file
Dim stream As IO.Stream = PostedFile.InputStream
Dim bytes As Byte()
ReDim bytes(stream.Length - 1)

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

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

Private Sub ReadFile( _
ByVal Connection As OleDbConnection _
)
Dim command As New OleDbCommand( _
"ImageBlobSelect", _
Connection _
)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@Id", 1)

Dim reader As OleDbDataReader = command.ExecuteReader()
reader.Read()
Dim bytes As Byte() = CType(reader.GetValue(0), Byte())
Dim stream As MemoryStream = New MemoryStream(bytes)
Dim image As Image

' Save the image to disk
Try
image = Image.FromStream(stream)
image.Save( _
IO.Path.Combine( _
Server.MapPath("~/uploads"), _
"uploaded_file.jpg" _
) _
)
Console.WriteLine("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
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...
9
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...
1
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...
1
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...
8
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...
6
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
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
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...
12
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.