Share via


Vb Net MemoryStream - load image \ byte and read it

Question

Monday, February 20, 2012 11:53 AM

i try to load image \ byte to memory and read it in memory (not from file - string)
with FileStream i do it like FileStream(image, IO.FileMode.Open) image = string of file path
so i want to do it with MemoryStream(image) image = image \ byte
i try many things but still cant get it

in msdn they have this example but not work for me
Using FS As New IO.MemoryStream(image)
FS.Write(image, 0, image.Length)
FS.Seek(0, IO.SeekOrigin.End)

any one know how i can do it
tnx
 

EDIT - last q' is how to convert  

FileStream(image, IO.FileMode.Open)

to

MemoryStream

All replies (81)

Thursday, February 23, 2012 7:56 PM ✅Answered | 1 vote

I created a small bitmap named  test.bmp file in Photoshop, then edited the file to add "|*" at the end. I imported it as a resource and set its build action to embed resource. I was then able to read the data from the end with this:

Module Module1

    Sub Main()
        ' write out the names of the resources as a check
        Dim ns = Reflection.Assembly.GetExecutingAssembly.GetManifestResourceNames
        For Each n In ns
            Console.WriteLine(n)
        Next

        ' this might be the important line
        Dim ims = Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream("ConsoleApplication1.test.bmp")

        If ims Is Nothing Then
            Console.WriteLine("nothing")
        Else
            Console.WriteLine(ims.Length)

            ims.Position = ims.Length - 5
            Dim b As Byte
            While ims.Position < ims.Length
                b = CByte(ims.ReadByte)
                Console.WriteLine(Chr(b))
            End While

            ims.Close()
        End If

        Console.ReadLine()

    End Sub

End Module

Which gave an output of

ConsoleApplication1.Image1.bmp
ConsoleApplication1.test.bmp
ConsoleApplication1.Resources.resources
826
ß


|
*

As you an see, the "|*" is present at the end.

Is that any help?

Andrew


Monday, February 20, 2012 1:43 PM

Hi, this creates an image, saves it to a MemoryStream and loads it from that stream:

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'memorystream to save the image
        Dim ms As New IO.MemoryStream()
        Using bmp As New Bitmap(400, 300)
            Using g As Graphics = Graphics.FromImage(bmp)
                g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
                g.Clear(Color.Green)
                g.FillEllipse(Brushes.Red, New Rectangle(0, 0, bmp.Width, bmp.Height))
            End Using

            'save to memorystream
            bmp.Save(ms, Imaging.ImageFormat.Png)
        End Using

        'now load from memorystream
        Dim bmp2 As New Bitmap(ms)
        'create a copy, so the memorystream can be disposed
        Me.BackgroundImage = New Bitmap(bmp2)
        'cleanup1
        ms.Dispose()
    End Sub

    Private Sub Form1_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        'cleanup2
        If Not Me.BackgroundImage Is Nothing Then
            Me.BackgroundImage.Dispose()
        End If
    End Sub
End Class

Regards,

  Thorsten


Monday, February 20, 2012 2:12 PM

thanks for ur reply

what im trying to do is this

read it from

PictureBox

or

Resources

Dim MS As New IO.MemoryStream()

Using FS As New IO.MemoryStream(MS.ToArray())

'FS.Write(image, 0, image.Length)

and read it again

FS.Seek(0, IO.SeekOrigin.End)

image.Save(MS, Imaging.ImageFormat.Png)


Monday, February 20, 2012 2:21 PM

Ok, let's see...

What have you got? An Image in a Picturebox? And what do you want to do with it? Why save it to a stream and read it back? So, what is your [overall] intention?

Regards,

  Thorsten


Monday, February 20, 2012 2:24 PM

i want to read info i bind in the image


Monday, February 20, 2012 10:50 PM

 

what im trying to do is this

read it from

PictureBox

or

Resources

Dim MS As New IO.MemoryStream()

image.Save(MS, Imaging.ImageFormat.Png)

Using FS As New IO.MemoryStream(MS.ToArray())

'FS.Write(image, 0, image.Length)

and read it again

FS.Seek(0, IO.SeekOrigin.End)

in msdn they have this example but not work for me
Using FS As New IO.MemoryStream(image)
FS.Write(image, 0, image.Length)
FS.Seek(0, IO.SeekOrigin.End)

any one know how i can do it
tnx


Monday, February 20, 2012 11:31 PM

Your description is confusing because this is not complete code and the comments don't make sense. There's a Using statement but no End Using. You write "and read it again" but you don't read it. Instead you only set the position in the stream. The line "FS.Seek(0, IO.SeekOrigin.End)" puts the position to the end of the stream. Is this intended? You write that the MSDN example doesn't work, but you show an incomplete example that writes to the stream. Does this writing fail?

   

Armin


Tuesday, February 21, 2012 8:35 AM

ok here i read the image to memory

Dim MS As New IO.MemoryStream()

image.Save(MS, Imaging.ImageFormat.Png)

now i need to read it again in memory

Using FS As New IO.MemoryStream(MS.ToArray())

here i begin to read it

FS.Seek(0, IO.SeekOrigin.End)

but its not working 

how i can read it again in memory after i load it


Tuesday, February 21, 2012 9:56 AM

There is nothing to read after SeekOrigin.End.  No need to seek FS.  You can read it from MS using SeekOrigin.Begin.


Tuesday, February 21, 2012 10:36 AM

if i understand u i use it like this

Public Sub Memory(ByVal image As Byte())

FS As New IO.MemoryStream(image)

FS.Seek(0, IO.

SeekOrigin.Begin)

While Not FS.ReadByte = Asc("|")

FS.Position -= 2

End While

and if u can to give me example


Tuesday, February 21, 2012 11:07 AM

The position of a new stream is 0.  You can position it wherever you want it using Seek.


Tuesday, February 21, 2012 11:38 AM

still cant get it work

when i use FileStream its work

but i need MemoryStream

Using FS As New IO.FileStream(image, IO.FileMode.Open)

FS.Seek(0, IO.

SeekOrigin.End)

While Not FS.ReadByte = Asc("|")

FS.Position -= 2

End While


Tuesday, February 21, 2012 11:44 AM

What doesn't work?  What are you trying to do with your While loop?  If it works with a FileStream and you want a MemoryStream, construct a MemoryStream using File.ReadAllBytes as the array for the constructor.


Tuesday, February 21, 2012 12:04 PM

MemoryStream dont work ( with byte = My.Resources , PictureBox1.image)

FileStream work ( with string = file ) example above

i want to do it with byte / image and use MemoryStream


Tuesday, February 21, 2012 12:07 PM

Probably it is easier if you tell what your goal is, than that you tell that your code does not work and don't tell what it in your idea should do.

Success
Cor


Tuesday, February 21, 2012 12:08 PM

As said before, "FS.Seek(0, IO.SeekOrigin.End)" puts the position at the end of the stream. You must set the position to the start of the stream:

      FS.Seek(0, IO.SeekOrigin.Begin)

After that, you can create the Image from the Stream. That part is missing, yet:

     dim img as Image
     img = Drawing.Image.FromStream(FS)

Armin


Tuesday, February 21, 2012 12:10 PM

ok i have image that i bind info in it and i want to read the info

now like i say from file (FileStream) its work

but i want to do it not from file so i need to use MemoryStream


Tuesday, February 21, 2012 12:15 PM

Yea but what you want as result of that memory stream, a ByteArray?

I;ve cutted a piece of code from our website

    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        'Reading a picture from disk and put it in a bytearray
        Using fo As New OpenFileDialog With
            {.Filter = "JpG (*.jpg)|*.jpg|Gif (*.gif)|*.gif|All files (*.*)|*.*"}
            If fo.ShowDialog = DialogResult.OK Then
                Dim fs As New IO.FileStream(fo.FileName, _
               IO.FileMode.Open)
                Dim br As New IO.BinaryReader(fs)
                Dim byteArray = br.ReadBytes(CInt(fs.Length))
                br.Close()
                'just to show the sample without a fileread error
                Dim ms As New IO.MemoryStream(byteArray)
                Me.PictureBox1.Image = Image.FromStream(ms)
            End If
        End Using
    End Sub

Success
Cor


Tuesday, February 21, 2012 12:23 PM

here the example that work and how i do it now how i make it work with MemoryStream (with byte = My.Resources or PictureBox1.image)

Using FS As New IO.FileStream(image, IO.FileMode.Open)                FS.Seek(0, IO.SeekOrigin.End)                While Not FS.ReadByte = Asc("|")                    FS.Position -= 2                End While                Dim s As String = Nothing                While Not FS.Position = FS.Length - 4                    s &= Chr(FS.ReadByte.ToString)                End While                Dim Ext As String = Nothing                FS.Seek(0, IO.SeekOrigin.End)                While Not FS.ReadByte = Asc("*")                    FS.Position -= 2                End While                While Not FS.Position = FS.Length                    Ext &= Chr(FS.ReadByte.ToString)                End While                FS.Seek(FS.Length - ((s.Length + s) + 5), IO.SeekOrigin.Begin)                While Not FS.Position = FS.Length - (s.Length + 5)                    Dim Data As Byte() = New Byte(FS.Position) {}                    FS.Read(Data, 0, Data.Length)                    FS.Close()                End While

Tuesday, February 21, 2012 1:20 PM

Yea that is your code and what do you want to do with that Byte Array.

That is all the time the question, like you show it, it seems to be very inefficient.

Success
Cor


Tuesday, February 21, 2012 1:23 PM

WTF is the code doing?? What do you expect it to do? There must be something you haven't mentioned yet.

Armin


Tuesday, February 21, 2012 1:24 PM

at the end save the byte to file
i try to use it like this

Using FS As New IO.MemoryStream(image) 'image = byte()

FS.Seek(0, IO.

SeekOrigin.End)

but not work

Edit - i gave all the info the code is open the image read the info at the end u get the info byte

"i have image that i bind info in it and i want to read the info from it and save it"


Tuesday, February 21, 2012 2:06 PM

... double post?

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/ec6fd9dd-3d86-479f-ad1a-6a9cc860882b

Regards,

  Thorsten


Tuesday, February 21, 2012 2:12 PM

yhe sorry just sign up here , its  in Windows Forms General , i dont know what to do and open in vb net new one .


Tuesday, February 21, 2012 3:52 PM

... double post?

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/ec6fd9dd-3d86-479f-ad1a-6a9cc860882b

Regards,

  Thorsten

Thanks!  I try not to answer double posts.  Particularly where the OP abandons one thread and posts another.


Tuesday, February 21, 2012 4:18 PM

... double post?

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/ec6fd9dd-3d86-479f-ad1a-6a9cc860882b

Regards,

  Thorsten

Thanks!  I try not to answer double posts.  Particularly where the OP abandons one thread and posts another.

yhe sorry just sign up here , its  in Windows Forms General , and i didnt know , so i open in vb net new one .


Wednesday, February 22, 2012 2:43 AM

Hi,

The main question here is the MemoryStream. So, it should be supported in VB.Net forum. So, we should merge your second post to the first post and move it to the VB.Net. There are experts will help you and give you the solutions. Thank you for undertandings.

For your issues, I am not sure why do you need to use the SeekOrigin.End. It will help and merge the stream to the previews file. So, you will get muilty arrays in the same files. If you need to read it again, you will need to divide these arrays and each of it can be load as an image which you saved before.

But, you can not read the whole stream and load it as image.

Another solution here is to use the Serialize/deserialize your images to a List<Image>, you can save them both in a binary file and a xml file.

I think it is much easier.

Best Regards

Neddy Ren[MSFT]
MSDN Community Support | Feedback to us


Wednesday, February 22, 2012 2:53 AM

"i have image that i bind info in it and i want to read the info from it and save it"

What kind of information are you talking about? We are only used to read and write images without further information. How would the information get into the image?

Armin


Wednesday, February 22, 2012 3:08 AM | 1 vote

"i have image that i bind info in it and i want to read the info from it and save it"

What kind of information are you talking about? We are only used to read and write images without further information. How would the information get into the image?

Armin

I think he has written something on the end of an image file.  He can recover what he has written from the file, but he wants to recover it from the image.  The image codec reads the image and ignores what he has added so he can't recover it from the stream the image is saved to.


Wednesday, February 22, 2012 5:01 AM

I did think so! And I think Neddy's replies are for the questions.

Knowledge will change the destiny.


Wednesday, February 22, 2012 9:52 AM

its to complicated for me i need example to understand how to read MemoryStream

and what the different in memory between

1. IO.FileStream(image, IO.FileMode.Open)

2. IO.MemoryStream(image)

3. Dim MS As New IO.MemoryStream()

image.Save(MS, Imaging.ImageFormat.Png)

dim img as Image = Drawing.Image.FromStream(MS)


Wednesday, February 22, 2012 11:49 AM

its to complicated for me i need example to understand how to read MemoryStream

and what the different in memory between

1. IO.FileStream(image, IO.FileMode.Open)

2. IO.MemoryStream(image)

3. Dim MS As New IO.MemoryStream()

image.Save(MS, Imaging.ImageFormat.Png)

dim img as Image = Drawing.Image.FromStream(MS)

You got already working code how to use the memorystream to load/save an image.

The part we have a problem with is that you want to store/read "additional information" in the memory stream. You are writing complicated loops and are looking for "|". This part we don't understand.

The three versions above:

  1. IO.FileStream(image, IO.FileMode.Open)

    Do you mean
        stream = New IO.FileStream(imagePath, IO.FileMode.Open)
    ?

  2. IO.MemoryStream(image)

    This lines is not executable code. What type is "image" in this case?

  3. Dim MS As New IO.MemoryStream()      'creates a new MemoryStream.

    image.Save(MS, Imaging.ImageFormat.Png)   'saves an image into a MemoryStream

    dim img as Image = Drawing.Image.FromStream(MS)    'creates a new image read from a MemoryStream

Armin


Wednesday, February 22, 2012 12:14 PM

i gave example that work for me with FileStream (from file)

what i dont understand is how FileStream is different from MemoryStream in storing the data in memory

if they dont different the code above (MemoryStream) will work the same as FileStream

Using FS As New IO.FileStream(image, IO.FileMode.Open) 'image = file

and

Using FS As New IO.MemoryStream(image) 'image = byte()

so they storing data different or in different way

i want to know how to use MemoryStream to do what FileStream do


Wednesday, February 22, 2012 12:28 PM | 1 vote

i gave example that work for me with FileStream (from file)

what i dont understand is how FileStream is different from MemoryStream in storing the data in memory

if they dont different the code above (MemoryStream) will work the same as FileStream

Using FS As New IO.FileStream(image, IO.FileMode.Open) 'image = file

and

Using FS As New IO.MemoryStream(image) 'image = byte()

so they storing data different or in different way

i want to know how to use MemoryStream to do what FileStream do

  • "what i dont understand is how FileStream is different from MemoryStream in storing the data in memory"

The difference is that only the MemoryStream is storing data in memory. The FileStream is reading/writing data from a file. Both are streams and work equally as to loading/saving images.

  • "Using FS As New IO.FileStream(image, IO.FileMode.Open) 'image = file

    and

    Using FS As New IO.MemoryStream(image) 'image = byte()"

After both lines you can write:
      
       dim img as Image
       img = image.fromStream(FS)

There is no difference because both are streams. Data is not stored differently. Why do you think so?

Armin


Wednesday, February 22, 2012 12:41 PM

ok so how i convert it i understand that with MemoryStream its complicated to read

img = image.fromStream(FS)

can i use the img like i use the file with FileStream

or is there any other way


Wednesday, February 22, 2012 12:45 PM

ok so how i convert it i understand that with MemoryStream its complicated to read

img = image.fromStream(FS)

can i use the img like i use the file with FileStream

or is there any other way

I don't understand the problem. You can load an image from a MemoryStream like you load it from a FileStream. There is no difference.

Armin


Wednesday, February 22, 2012 12:54 PM | 1 vote

The only thing that comes into my mind is that you should be using the "Using" statement carefull. Don't dispose the stream because the Image uses it. But that's true for the MemoryStream and for the FileStream.

Armin


Wednesday, February 22, 2012 12:55 PM

so why its not working

1. Dim MS As New IO.MemoryStream()  

2. image.Save(MS, Imaging.ImageFormat.Png) 'save an image into a MemoryStream

3. Using FS As New IO.MemoryStream(MS)

and the problem is that i want to read it again (in 3)


Wednesday, February 22, 2012 12:57 PM

so why its not working

1. Dim MS As New IO.MemoryStream()  

2. image.Save(MS, Imaging.ImageFormat.Png) 'save an image into a MemoryStream

3. Using FS As New IO.MemoryStream(MS)

and the problem is that i want to read it again (in 3)

After step 2, the stream position is at the end. In order to read the image, you must set the position to the start before step 3:

    MS.Seek(0, SeekOrigin.Begin)

That's what we already wrote several messages before.

Armin


Wednesday, February 22, 2012 1:07 PM

Dim MS As New IO.MemoryStream()

image.Save(MS, Imaging.

ImageFormat.Png)

Using FS As New IO.MemoryStream(MS.ToArray())

i try like this with seek and without not work  

i think what JohnWein say is the problem

The image codec reads the image and ignores what he has added so he can't recover it from the stream the image is saved to


Wednesday, February 22, 2012 4:55 PM

Dim MS As New IO.MemoryStream()

image.Save(MS, Imaging.

ImageFormat.Png)

Using FS As New IO.MemoryStream(MS.ToArray())

i try like this with seek and without not work  

i think what JohnWein say is the problem

The image codec reads the image and ignores what he has added so he can't recover it from the stream the image is saved to

I've tried exactly your code and added one line:

   Dim img = image.FromStream(FS)

It works.

Armin


Wednesday, February 22, 2012 5:13 PM

What seems to be all the confusion?  After saving the image to the memory stream, reset the stream position to 0 and then create a new image from the stream:

Public Class Form1
    Private SourcePictureBox As New PictureBox
    Private TargetPictureBox As New PictureBox

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'Setup example form
        SourcePictureBox.BorderStyle = BorderStyle.Fixed3D
        Controls.Add(SourcePictureBox)
        TargetPictureBox.Left = SourcePictureBox.Width
        TargetPictureBox.BorderStyle = BorderStyle.Fixed3D
        Controls.Add(TargetPictureBox)

        'Create initial test image
        SourcePictureBox.Image = SystemIcons.Application.ToBitmap

        'Save image to memorystream
        Dim ms As New System.IO.MemoryStream
        SourcePictureBox.Image.Save(ms, Imaging.ImageFormat.Png)

        'Read stream into new image instance
        ms.Position = 0
        Dim imageCopy As Image = Image.FromStream(ms)
        ms.Close()
        
        'Set second picturebox to image copy
        TargetPictureBox.Image = imageCopy
    End Sub
End Class

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Wednesday, February 22, 2012 6:05 PM

Dim MS As New IO.MemoryStream()            image.Save(MS, Imaging.ImageFormat.Png)            'Dim img As Image = image.FromStream(MS)            Using FS As New IO.MemoryStream(MS.ToArray())                FS.Seek(0, IO.SeekOrigin.End)                While Not FS.ReadByte = Asc("|")                    FS.Position -= 2                End While                Dim s As String = Nothing                While Not FS.Position = FS.Length - 4                    s &= Chr(FS.ReadByte.ToString)                End While                Dim Ext As String = Nothing                FS.Seek(0, IO.SeekOrigin.End)                While Not FS.ReadByte = Asc("*")                    FS.Position -= 2                End While                While Not FS.Position = FS.Length                    Ext &= Chr(FS.ReadByte.ToString)                End While                FS.Seek(FS.Length - ((s.Length + s) + 5), IO.SeekOrigin.Begin)                While Not FS.Position = FS.Length - (s.Length + 5)                    Dim Data As Byte() = New Byte(FS.Position) {}                    FS.Read(Data, 0, Data.Length)                    FS.Close()

its work if u dont need to read it again what with loops ?
i have try all the options i could imagine include the all replys code


Wednesday, February 22, 2012 6:16 PM

"What seems to be all the confusion?  After saving the image to the memory stream, reset the stream position to 0 and then create a new image from the stream:"

How do you add text onto the end of an image stream and keep it there while loading and saving the image?  Confused?  So is everyone else.


Wednesday, February 22, 2012 6:19 PM

See my Steganographer program at johnweinhold.com.  It embeds text in the pixels of the image.
What is the length of your FileStream and your MemoryStream?


Wednesday, February 22, 2012 6:54 PM

for sure very very Confused i miss something like always and at the end its very simple

something i take as simple is wrong i will take a look at ur example tnx

Edit - i have image

Dim MS As New IO.MemoryStream() image.Save(MS, Imaging.ImageFormat.Png) MS.Position = 0 Dim img As Image = image.FromStream(MS) MS.Close()

to read it i need MemoryStream so again new MemoryStream this what i dont understand

i need now byte to read and i have image so i have to convert it to byte

sorry but can some1 just save my time and write the code how i read the inage i spend lots of time for this i give up


Wednesday, February 22, 2012 9:00 PM

"What seems to be all the confusion?  After saving the image to the memory stream, reset the stream position to 0 and then create a new image from the stream:"

How do you add text onto the end of an image stream and keep it there while loading and saving the image?  Confused?  So is everyone else.

LOL I am now...

I guess I didnt get the part about extra data in the stream; I see that in your previous reply now.

Do you think he is trying to work with meta data on the file?  Maybe its not an arbitrary string at the end of the image stream but actual file meta data...

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Wednesday, February 22, 2012 9:29 PM

to read the info (the loops) i need byte and u tell me to make it image

why i cant read the byte and get the info from the begining

and wein ur example make more Confused  then i was before


Wednesday, February 22, 2012 9:44 PM

Does this demonstrate the basic idea of what you are trying to do?

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'Create test image
        Dim originalImage As Image = SystemIcons.Application.ToBitmap
        Dim tempFilePath As String = System.IO.Path.GetTempFileName
        Dim strangeImageStream As System.IO.FileStream = System.IO.File.Open(tempFilePath, IO.FileMode.OpenOrCreate)
        originalImage.Save(strangeImageStream, Imaging.ImageFormat.Png)

        'Embedd extra data at end of image file
        Dim extraDataString As String = "|This is some extra text embedded at the end of the image."
        Dim extraDataBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(extraDataString)
        strangeImageStream.Write(extraDataBytes, 0, extraDataBytes.Length)
        strangeImageStream.Close()

        'Show proof of modified file
        Process.Start("Notepad.exe", tempFilePath)

        'Read raw file into byte array
        Dim sourceData() As Byte = System.IO.File.ReadAllBytes(tempFilePath)
        'Construct stream from the byte array for the image construction
        Dim desiredMemoryStream As New System.IO.MemoryStream(sourceData)
        'Search the byte array instead of the stream for your extra data
        Dim splitPointIndex As Integer = Array.LastIndexOf(sourceData, CByte(Asc("|")))

        'Create an image from the stream
        Me.BackgroundImage = Image.FromStream(desiredMemoryStream)
        'Reconstruct the extra data into text
        Me.Text = System.Text.Encoding.ASCII.GetString(sourceData.Skip(splitPointIndex).ToArray)

        'desiredMemoryStream.Close() !! Cannot close - Must keep stream open for lifetime of image: http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx
    End Sub
End Class

Obviously the exact logic to find the extra data is different (my simple example just needs the last pipe character). But is this what you are trying to do? You could still set the "desiredMemoryStream" position to 0 and then find the extra info using your loops after you've created the image instance. -edit- actually you might need to do that before you create the image... not sure how picky the image will be about the stream but since it must stay open you might be better to loop the stream first, reset the position to 0, and then create the image (assuming the seperate array isn't good enough for your purposes).

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Wednesday, February 22, 2012 9:56 PM

sorry but can some1 just save my time and write the code how i read the inage i spend lots of time for this i give up

Some messages above, you've posted code, I added one line, and it worked. You did not even answer. 

Look for the message containing "I've tried exactly your code and added one line"

EDIT: Now you will probably again start discussing about searching for "|" even though you did not even mention it in that message.

Armin


Wednesday, February 22, 2012 10:04 PM

yhe u got it finally some1 understand me

after u load the image the stream position is at the end

and if u read Neddy Ren reply u get the idea

'Construct stream from the byte array for the image construction
 Dim desiredMemoryStream As New System.IO.MemoryStream(sourceData) 'the stream position is at the end
 'Search the byte array instead of the stream for your extra data
 Dim splitPointIndex As Integer = Array.LastIndexOf(sourceData, CByte(Asc("|"))) 'here the array loops

so i try it already

Using FS As New IO.MemoryStream(byte())
                FS.Seek(0, IO.SeekOrigin.End)
                While Not FS.ReadByte = Asc("|")
                    FS.Position -= 2
                End While

this is my problem how to loop the array and why i cant loop the byte


Wednesday, February 22, 2012 10:24 PM

What problem are you having with that code?  I don't understand "...how to loop the array and why i cant loop the byte..." it doesnt make sense... what array?  and what do you mean by "loop the byte"?

At any rate, it seems to me that you may just be getting hung up on that Using statement.  First of all, note the comment in my sample - if you create an image from the stream, then then stream must remain open for the lifetime of the image.  So you cannot use a Using statement as it will close the stream as soon as the block ends.

Here is a modification to my previous example which does not use the seperate array of bytes for searching but rather uses the loop routine you posted (without the Using statement):

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'Create test image
        Dim originalImage As Image = SystemIcons.Application.ToBitmap
        Dim tempFilePath As String = System.IO.Path.GetTempFileName
        Dim strangeImageStream As System.IO.FileStream = System.IO.File.Open(tempFilePath, IO.FileMode.OpenOrCreate)
        originalImage.Save(strangeImageStream, Imaging.ImageFormat.Png)

        'Embedd extra data at end of image file
        Dim extraDataString As String = "|This is some extra text embedded at the end of the image."
        Dim extraDataBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(extraDataString)
        strangeImageStream.Write(extraDataBytes, 0, extraDataBytes.Length)
        strangeImageStream.Close()

        'Show proof of modified file
        Process.Start("Notepad.exe", tempFilePath)

        'Construct stream for all purposes
        Dim desiredMemoryStream As New System.IO.MemoryStream(System.IO.File.ReadAllBytes(tempFilePath))

        'Search the stream for the extra data
        desiredMemoryStream.Seek(0, IO.SeekOrigin.End)
        While Not desiredMemoryStream.ReadByte = Asc("|")
            desiredMemoryStream.Position -= 2
        End While

        'Read the extra data from the stream once found
        Dim dataBytes(desiredMemoryStream.Length - desiredMemoryStream.Position - 1) As Byte
        desiredMemoryStream.Read(dataBytes, 0, dataBytes.Length)

        'Reset the stream position
        desiredMemoryStream.Position = 0
        'Create an image from the stream
        Me.BackgroundImage = Image.FromStream(desiredMemoryStream)
        'Reconstruct the extra data into text
        Me.Text = System.Text.Encoding.ASCII.GetString(dataBytes)

        'desiredMemoryStream.Close() !! Cannot close - Must keep stream open for lifetime of image: http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx
    End Sub
End Class

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Wednesday, February 22, 2012 10:39 PM

ok its late im tierd and my brain not work thanks for ur help i will check it later and reply its look like what i want to

about Using statement i have the data so its not problem 

Dim Data As Byte() = New Byte(FS.Position) {}

FS.Read(Data, 0, Data.Length)

FS.Close()

loop the byte = read

bye


Wednesday, February 22, 2012 10:55 PM

So you cannot use a Using statement as it will close the stream as soon as the block ends.

Has also been said before. ^^

Armin


Thursday, February 23, 2012 10:38 AM

read what i write in my reply above u


Thursday, February 23, 2012 11:15 AM

read what i write in my reply above u

As long as I am not able to understand sentences like "loop the byte = read", I'm afraid, I'm outta here. I was talking to Reed, BTW.

Armin


Thursday, February 23, 2012 11:26 AM

@Armin,

I get the idea no1me is not reading the replies, he simply is waiting for a piece of code which he can copy and past and try.

However, because he is not reading he does not understand we cannot give him that code because we don't know what he wants to do with the code.

Every piece of code given in this thread will probalbly run, but that does code also for HelloWorld (I assume you see I'n not only writing this to you).

:-)

Success
Cor


Thursday, February 23, 2012 11:28 AM

Cor, I consider it a communication problem only. Anyway....

:)

Armin


Thursday, February 23, 2012 12:15 PM

ok i will give u my code so u can see my problem and test it

here how i bind to image

here how i Extract it (FileStream)

Public Sub FromImage(ByVal image As String)        Try            Using FS As New IO.FileStream(image, IO.FileMode.Open)                FS.Seek(0, IO.SeekOrigin.End)                While Not FS.ReadByte = Asc("|")                    FS.Position -= 2                End While                Dim s As String = Nothing                While Not FS.Position = FS.Length - 4                    s &= Chr(FS.ReadByte.ToString)                End While                Dim Ext As String = Nothing                FS.Seek(0, IO.SeekOrigin.End)                While Not FS.ReadByte = Asc("*")                    FS.Position -= 2                End While                While Not FS.Position = FS.Length                    Ext &= Chr(FS.ReadByte.ToString)                End While                FS.Seek(FS.Length - ((s.Length + s) + 5), IO.SeekOrigin.Begin)                While Not FS.Position = FS.Length - (s.Length + 5)                    Dim Data As Byte() = New Byte(FS.Position) {}                    FS.Read(Data, 0, Data.Length)                    FS.Close()                    'here i use the Data to save it                End While            End Using        Catch ex As Exception        End Try    End Sub

and u know already what i want to do

EDIT -  I don't understand "...how to loop the array and why i cant loop the byte..."  (Reed Kimble)


Thursday, February 23, 2012 1:17 PM

No.  We have no idea what you want to do.  What doesn't work about the code you posted in your last post?


Thursday, February 23, 2012 1:28 PM

this is the code that work with FileStream

i want to do it with  byte

FromImage(ByVal image As Byte())

and need to use MemoryStream

i hope finaly some1 will understand


Thursday, February 23, 2012 2:05 PM

Why would you want to do the same thing using a MemoryStream?  When you write an image and another file to a MemoryStream, nothing remains when you dispose the stream.  Until you dispose the stream, you can do the same thing with a MemoryStream that you do with a FileStream.


Thursday, February 23, 2012 2:23 PM

that i can do it form My.Resources

i dont need the image i need the info = Data this why i use FS.Close()

While Not FS.Position = FS.Length - (s.Length + 5)

                    Dim Data As Byte() = New Byte(FS.Position) {} FS.Read(Data, 0, Data.Length)
                   

                   FS.Close() ' with FileStream i dont need this just with MemoryStream

                    'here i use the Data to save it

                End While

and i already try with and with out dispose


Thursday, February 23, 2012 2:42 PM

that i can do it form My.Resources

At least in fact you don't need for that the memorystream, however here the sample code.

    'Set an image from the resources to a bytarray and then to a picturebox
    Private byteArray As Byte()
    Private Sub SetImageToByteArray_Click(sender As System.Object, e As System.EventArgs) Handles SetImageToByteArray.Click
        Using msX As New IO.MemoryStream
            DirectCast(My.Resources.TheImage, Image).Save(msX, Imaging.ImageFormat.Bmp)
            byteArray = msX.ToArray()
        End Using
        'Set it in a picturebox from the bytearray
        Using ms2 As New IO.MemoryStream(byteArray)
            Me.PictureBox2.Image = Image.FromStream(ms2)
        End Using
    
    End Sub

But to set an image in the resources can also be done with this.

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles SetResourceImageInPictureBox.Click
        PictureBox1.Image = My.Resources.Image
    End Sub

Success
Cor


Thursday, February 23, 2012 2:50 PM

You'll have to save the image and the file separately in My.Resources or save the stream as a byte array.


Thursday, February 23, 2012 3:08 PM

    Public Sub FromImage(ByVal imageBytes() As Byte)
        Try
            Using FS As New System.IO.MemoryStream(imageBytes)
                FS.Seek(0, IO.SeekOrigin.End)
                While Not FS.ReadByte = Asc("|")
                    FS.Position -= 2
                End While
                Dim s As String = Nothing
                While Not FS.Position = FS.Length - 4
                    s &= Chr(FS.ReadByte.ToString)
                End While
                Dim Ext As String = Nothing
                FS.Seek(0, IO.SeekOrigin.End)
                While Not FS.ReadByte = Asc("*")
                    FS.Position -= 2
                End While
                While Not FS.Position = FS.Length
                    Ext &= Chr(FS.ReadByte.ToString)
                End While
                FS.Seek(FS.Length - ((s.Length + s) + 5), IO.SeekOrigin.Begin)

                While Not FS.Position = FS.Length - (s.Length + 5)

                    Dim Data As Byte() = New Byte(FS.Position) {}
                    FS.Read(Data, 0, Data.Length)
                    FS.Close()

                    'here i use the Data to save it

                End While
            End Using
        Catch ex As Exception
        End Try
    End Sub

There is your exact routine modified to take a byte array instead of a file path and to build a memory stream out of the byte array instead of reading the file from disk. Though I still don't understand why you need the memory stream instead of just using the byte array.

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 3:16 PM

I don't find the OP too difficult to understand.  He wants to save his combined file as an image in My.Resources and reconstruct the image and the file from My.Resources.  Not an easy task. 


Thursday, February 23, 2012 3:23 PM

I don't find the OP too difficult to understand.  He wants to save his combined file as an image in My.Resources and reconstruct the image and the file from My.Resources.  Not an easy task. 

John,

The first part, is impossible, the resources are serialized in the assembly by the Visual Studio tools. 

For the second part I gave code 40 minutes ago.

Be aware that there also the old RESX files, but that is not related to the My.Resources Class in VB.

Success
Cor


Thursday, February 23, 2012 3:29 PM

Wouldn't this be the way to execute his logic against an item in the resources?

    Public Sub FromImage(ByVal resourceName As String)
        Try
            Using FS As System.IO.UnmanagedMemoryStream = My.Resources.ResourceManager.GetStream(resourceName)
                FS.Seek(0, IO.SeekOrigin.End)
                While Not FS.ReadByte = Asc("|")
                    FS.Position -= 2

Where "resourceName" is the name of the image resource in My.Resources.

This provides an unmanaged memory stream directly from the resource manager... should be what the OP is asking for, assuming the byte array they want to use is coming from reading this resource file.

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 3:46 PM

Reed,

I get more and more the idea that he/she is busy with an ole image which needs a later starting point to overcome the ofset like this.

 ms.Write(byteArray, 78, byteArray.Length - 78)

In fact something then for Paul 

Success
Cor


Thursday, February 23, 2012 4:52 PM

cor im he (no1ME) and not she

wein i dont want to save it to resources

reed already try it too that what i dont understand why its not work

i gave u guys this u can try to use it and see if its work

thanks for ur try to help


Thursday, February 23, 2012 5:01 PM

You say it doesnt work but you do not say how...

What result do you get?  What result do you expect?

The code you put in pastebin just creates your embedded data-image and saves it to disk; it has nothing to do with My.Resources...

You have not told us how this file saved to disk relates to your My.Resources...  how does the image you create with that code get into My.Resources?

You say you want to modify the filestream code to read from a byte array... ok fine, where does the array come from?  What code are you using to get the byte array that you want to pass to FromImage()?

You have everything you need in this thread to solve the problem as stated.  Any issue you are still encountering must be the result of some part of the program which you are not telling us about.

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 5:02 PM

OK!  I officially join the ranks of the totally confused by the OP.

"that i can do it form My.Resources"

"wein i dont want to save it to resources"

What's next?


Thursday, February 23, 2012 5:10 PM

I think that somehow the image created using the code at pastebin is being added to the resources manually.  Then the desire is to simply get the embedded data out of the image in My.Resources; the image itself is not needed.

Ya know, when you add an image resource to My.Resources, the framework is creating a new image, loading it from the file, then serializing that to the resources, itsn't it?  So that means that the act of adding the modified file to My.Resources would strip the embedded data when the internal image instance was created and serialized to My.Resources.

If thats the case then this would never work using the file from Resources...

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 5:12 PM

wien read it from resources and not from file

reed "simple" bind image with my code put the bind image in picturebox TRY to extract the info


Thursday, February 23, 2012 8:05 PM

wien read it from resources and not from file

reed "simple" bind image with my code put the bind image in picturebox TRY to extract the info

You've been told that this will not work.  Once you create an image instance (the picture to put in the picturebox) the extra embedded data is gone (say embedded not bind - there is no binding going on here).

You must extract the extra data from the image bytes before you try to create an Image object instance.  It has been pointed out from the beginning that the image instance you show in VB will not contain the extra info.  The extra info is only in the binary representation which is on disk.

You said that you do not want the image, just the data.  So why is there now a picturebox involved?

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 8:06 PM

Good one Andrew!

So if using the designer to add to the Resources is indeed creating an Image instance and causing his embedded data to be lost, this should get around it.

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 8:15 PM

I did use the designer to add the resource, so it doesn't appear to remove any data at that stage.

(OT: does the Edit button for replies still mess up code? I wanted to go back and correct my typos, but I didn't want to mess up the code's markup, and I haven't found a test forum hereabouts.)

--
Andrew


Thursday, February 23, 2012 9:04 PM | 1 vote

I've edited code recently without undesired consequence.  But I can't guarantee your results.  =P

The OP will probably need stepped through that process... I have to assume that right now they are using My Project -> Resources -> Add Existing...

Reed Kimble - "When you do things right, people won't be sure you've done anything at all"


Thursday, February 23, 2012 9:28 PM | 1 vote

The OP will probably need stepped through that process... I have to assume that right now they are using My Project -> Resources -> Add Existing...

Right-click the solution name in Solution Explorer (ctrl-alt-L), choose Properties. Select the Resources tab on the left, in the Add Resource drop-down at the top choose Add Existing File... and add the file. In Solution Explorer, navigate to the file in the Resources section, right-click it and choose Properties. Click the drop-down expander (terminology?) and choose Embedded Resource. Et voilà, my code works.

I've edited code recently without undesired consequence. But I can't guarantee your results. =P

I'll try it some time. Cheers :)

--
Andrew


Saturday, February 25, 2012 8:29 PM

i just back . i will check the example

tnx u all for the help

BIG EDIT -  i try it as Embedded Resource and didnt work (My.Resources.image)

so its not work directly ?

Andrew ur code work with

Assembly.GetExecutingAssembly.GetManifestResourceStream

i add try catch to pass a problem but its work tnx

reed tnx for ur help this thread have lots of misunderstanding i will try to be more clear next