Getting images into byte arrays

R

RichardF

Can anyone tell me what is wrong with this code?

I want to get the ocntents of the JPEG image into a byte array. After
the theStream.read call, the theBytes array is still filled with all
nulls. and iCount is zero.

I used this article
(http://msdn.microsoft.com/library/d.../html/frlrfsystemiomemorystreamclasstopic.asp)
as a starting point.

Eventually, what I want to have a function that will read an image
from disk in any format (BMP, TIF, JPG etc), convert it to some other
format, and then return it in a Byte array


Thanks for any help

RichardF



Imports System
Imports System.IO
Imports System.Text
Imports System.Drawing

Module Module1

Sub Main()

Dim theImage As Image
Dim theStream As New MemoryStream
Dim theBytes As Byte()
Dim iCount As Integer

Try
theImage = Image.FromFile("C:\Images\Test.jpg")
theImage.Save(theStream, Imaging.ImageFormat.Jpeg)
theBytes = New Byte(theStream.Length - 1) {}
iCount = theStream.Read(theBytes, 0, theStream.Length - 1)
Catch ex As Exception
End Try

End Sub

End Module
 
M

MarkR

I think you should try the Image.LockBits() function to access the image
contents, rather than reading back from a stream. This site is for C#, but
the algorithm should be apparent -- essentially, you call LockBits for a
portion of the image, then walk the BitmapData array.
http://www.codeproject.com/cs/media/csharpgraphicfilters11.asp

If you insist on reading from the stream, I suspect you need to find a way
to flush the stream. I'm not directly familiar with the function, but maybe
there's a Stream.Flush() or Stream.Close() function that will ensure your
StreamReader has the latest version...

Good luck,
/m
 
J

Jon Skeet [C# MVP]

RichardF said:
Can anyone tell me what is wrong with this code?

I want to get the ocntents of the JPEG image into a byte array. After
the theStream.read call, the theBytes array is still filled with all
nulls. and iCount is zero.

You're writing to the stream, but then not "rewinding" the stream to
the start again before you're reading it.

Set the position to 0 before the read.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top