Solved

Image.FromStream

Posted on 2003-12-02
15
1,451 Views
Last Modified: 2007-12-19
Alright. I'm trying to load a Bitmap (or a TIFF File, but one step at a time here people) into a MemoryFile to be used and quickly discarded (the program can interact faster with it that way, correct?)
So then!!
here is my current progress, Amazingly enough it compiles and runs (somewhat).
/********************
CreateMMFile takes a BinaryReader object defined in the "HandleFileType" Method.
********************/
      public static void HandleFileType(string Filename)
      {
            Image ocrImage = Image.FromFile(Filename);
            byte[] bitmap32 = new byte[3]
                  {66,208,3};
            byte[] tif14 = new byte[3]
                  {73,0,8};
            byte[] imgBytes = new byte[3]
                  {0,0,0};

            if(Filename.Length != 0)
            {
                  using (BinaryReader brFile = new BinaryReader(
                                 new FileStream(Filename,FileMode.Open,FileAccess.Read,
                                 FileShare.Read)))
                  {

                        imgBytes[0] = (byte)brFile.BaseStream.ReadByte();
                        imgBytes[1] = (byte)brFile.BaseStream.ReadByte();
                        imgBytes[2] = (byte)brFile.BaseStream.ReadByte();

                        if(imgBytes[0] == bitmap32[0])
                        {
                              CreateMMFile(brFile);
                        }
                        if(imgBytes[0] == tif14[0])
                        {
// Image is a TIFF File
                        }
                  }
            }
      }
      public static void CreateMMFile(BinaryReader bmpFile)
      {
            byte[] buffer = new byte[bmpFile.BaseStream.Length];
            byte[] imgBinary = new byte[bmpFile.BaseStream.Length];
            IntPtr MMFile = IntPtr.Zero;

            MemoryStream msStream = new MemoryStream(buffer,0,buffer.Length,true,true);

            for(int i = 0;i < bmpFile.BaseStream.Length - 1; i++)
            {
                  imgBinary[i] = (byte)bmpFile.BaseStream.ReadByte();
            }
            using (BinaryWriter bwFile = new BinaryWriter(msStream))
            {
                  bwFile.Write(imgBinary);
            }
      }

My Question is .. Is this doing what I think it is doing, and how can I get the Data from Memory and load it as an Image Object?
0
Comment
Question by:derekthornton
  • 8
  • 7
15 Comments
 
LVL 22

Expert Comment

by:_TAD_
ID: 9861482


take a look at this code...


                  Stream inputFile = new FileStream(@"C:\temp\myPic.jpg",FileMode.Open);
            byte[] buff = new byte[inputFile.Length];
                  inputFile.Read(buff,0,buff.Length);

                  Stream memStream = new MemoryStream(buff);

                  Image im = Image.FromStream(memStream);
0
 
LVL 22

Expert Comment

by:_TAD_
ID: 9861561


In a nutshell....

Open a new stream (of type filestream)
read all of the contents of the file into a byte array
Open a new Stream (of type MemoryStream) using the array of bytes from the file stream
Create an image from a stream
0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861690
Doesn't work. I get an Invalid Parameter Exception.
0
 
LVL 22

Expert Comment

by:_TAD_
ID: 9861755


You did copy and paste the code directly, right?

I have a form with a picture box and a button on it (that's it), and this code works perfectly:


            private void button1_Click(object sender, System.EventArgs e)
            {
                  Stream inputFile = new FileStream(@"C:\temp\frog.jpg",FileMode.Open);
            byte[] buff = new byte[inputFile.Length];
                  inputFile.Read(buff,0,buff.Length);

                  Stream memStream = new MemoryStream(buff);

                  Image im = Image.FromStream(memStream);

                  pictureBox1.Image = im;
            }
0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861789
That can't work. It can't have a Designated path name. It has to take the filename from another process that examined the image to begin with.
0
 
LVL 22

Expert Comment

by:_TAD_
ID: 9861793


In fact.... just so that there is no confusion, send back a thumbnail image (resized to the size of the textbox);



            private void button1_Click(object sender, System.EventArgs e)
            {
                  Stream inputFile = new FileStream(@"C:\temp\frog.jpg",FileMode.Open);
            byte[] buff = new byte[inputFile.Length];
                  inputFile.Read(buff,0,buff.Length);

                  Stream memStream = new MemoryStream(buff);

                  Image im = Image.FromStream(memStream);

                  pictureBox1.Image = im.GetThumbnailImage(pictureBox1.Width,pictureBox1.Height,null,IntPtr.Zero);
            }

0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861800
It keeps telling me the file is being used by another process, how can I free up the File from the previous BinaryReader stream?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 22

Accepted Solution

by:
_TAD_ earned 500 total points
ID: 9861814

okay.... replace the string with the variable name with the fully qualified path name (no @ symbol)
          private string MyFilePath = @"C:\temp\frog.jpg";
          private string MyFilePath = "C:\\temp\\frog.jpg";   // same thing as above, no @ symbol



          private void button1_Click(object sender, System.EventArgs e)
          {
               Stream inputFile = new FileStream(MyFilePath, FileMode.Open);
            byte[] buff = new byte[inputFile.Length];
               inputFile.Read(buff,0,buff.Length);

               Stream memStream = new MemoryStream(buff);

               Image im = Image.FromStream(memStream);

               pictureBox1.Image = im.GetThumbnailImage(pictureBox1.Width,pictureBox1.Height,null,IntPtr.Zero);
          }

0
 
LVL 22

Expert Comment

by:_TAD_
ID: 9861826


You have to close the binaryreader object.
0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861828
But the file is still in use by Binary Reader. I have to have the file open to do what I need to do, but I have to close it to have it be read by the FileStream.
0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861833
I DO close the BinaryReader object and it does nothing. It STILL tells me it's open. Do I have to close a specific part of the binaryReader?
0
 
LVL 22

Expert Comment

by:_TAD_
ID: 9861854


your other option is to set the file share on your file stream.   In my example it would look like:

Stream inputFile = new FileStream(@"C:\temp\frog.jpg",FileMode.Open, FileAccess.Read, FileShare.Read);

0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861860
     This might make things clearer.

public static void HandleFileType(string Filename,TOCRJobInfo mJobInfo,
            ListBox lst,PictureViewer.PictureViewer Viewer)
      {

            Image ocrImage = Image.FromFile(Filename);
            byte[] bitmap32 = new byte[3]
                  {66,208,3};
            byte[] tif14 = new byte[3]
                  {73,0,8};
            byte[] imgBytes = new byte[3]
                  {0,0,0};

            if(Filename.Length != 0)
            {
                  using (BinaryReader brFile = new BinaryReader(
                                 new FileStream(Filename,FileMode.Open,FileAccess.ReadWrite,
                                 FileShare.ReadWrite)))
                  {

                        imgBytes[0] = (byte)brFile.BaseStream.ReadByte();
                        imgBytes[1] = (byte)brFile.BaseStream.ReadByte();
                        imgBytes[2] = (byte)brFile.BaseStream.ReadByte();

                        if(imgBytes[0] == bitmap32[0])
                        {
                              CreateMMFile(brFile,lst,Viewer,Filename);
                              mJobInfo.InputFile = Filename;
                              mJobInfo.JobType = OCRuser.TOCRJOBTYPE_DIBFILE;
                              mJobInfo.PageNo = ocrImage.GetFrameCount(FrameDimension.Page);
                        }
                        if(imgBytes[0] == tif14[0])
                        {
                              
                              mJobInfo.JobType = OCRuser.TOCRJOBTYPE_TIFFFILE;
                              mJobInfo.PageNo = ocrImage.GetFrameCount(FrameDimension.Page);
                        }
                  }
            }
      }

      public class DoWriteNums
      {
            private byte[] buffer;
            private ListBox lst;

            public DoWriteNums(ListBox lst,byte[] buffer)
            {
                  this.lst = lst;
                  this.buffer = buffer;
            }
            public void Execute()
            {
                  for(int i=0;i<buffer.Length-1;i++)
                  {
                        lst.Items.Add(buffer[i].ToString());
                  }
            }
      }
      public static void CreateMMFile(BinaryReader bmpFile,ListBox lst,
            PictureViewer.PictureViewer Viewer,string Filename)
      {
            string FileNameTemporary = Filename.Substring(Filename.Length-4);
            string FileNameTemporaryPath = Filename.Substring(0,Filename.Length-4);
            
            string FileNameNew = FileNameTemporaryPath + "temp" + FileNameTemporary;

            bmpFile.BaseStream.Close();
      
            Stream inputFile = new FileStream(Filename,FileMode.Open);
            byte[] buffer = new byte[inputFile.Length];
            inputFile.Read(buffer,0,buffer.Length);

            Stream memStream = new MemoryStream(buffer);
            Image im = Image.FromStream(memStream);
            Viewer.LoadImage(im);

            Thread myThread = new
                  Thread(new ThreadStart(new DoWriteNums(lst,buffer).Execute));
            myThread.Start();

            MemoryStream msStream = new MemoryStream(buffer,0,buffer.Length,true,true);
      }
0
 
LVL 2

Author Comment

by:derekthornton
ID: 9861891
What if I closed brFile before my If Statements?
0
 
LVL 22

Expert Comment

by:_TAD_
ID: 9862269


I think your issue starts with this line of code:

 using (BinaryReader brFile = new BinaryReader(
                            new FileStream(Filename,FileMode.Open,FileAccess.ReadWrite,
                            FileShare.ReadWrite)))  
{

//stuff here

}



It appears as if you've got your file share property set properly on your filestream, but it is embeded in the binaryWriter object.


Just for giggles, I would take out the "using" statement and just dispose of your objects the long way for right now.  It allows for a little more control and it may be easier to see what is going wrong.


0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now