473,778 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get JPG from MJPG Stream Problem

6 New Member
Greetings,

I am trying to get a JPG Frame from a MJPG Stream. A MJPG is basically a stream of JPGs which are splitted by a special boundary string. So I tried to get the stream, split it by the boundary strings and save the JPG binary data into a file.

The problem is, I cant save the data into a proper JPG file which I then open. This is my code:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Net;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Drawing.Imaging;
  9.  
  10. namespace JPGFroCGI
  11. {
  12.     class Program
  13.     {
  14.  
  15.         public string GetStringFromByte(byte[] dBytes)
  16.         {
  17.             System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  18.             return enc.GetString(dBytes);
  19.  
  20.         }
  21.  
  22.         public static byte[] StrToByteArray(string str)
  23.         {
  24.             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  25.             return encoding.GetBytes(str);
  26.         }
  27.  
  28.         private string[] SplitByString(string testString, string split)
  29.         {
  30.             int offset = 0;
  31.             int index = 0;
  32.             int[] offsets = new int[testString.Length + 1];
  33.  
  34.             while (index < testString.Length)
  35.             {
  36.                 int indexOf = testString.IndexOf(split, index);
  37.                 if (indexOf != -1)
  38.                 {
  39.                     offsets[offset++] = indexOf;
  40.                     index = (indexOf + split.Length);
  41.                 }
  42.                 else
  43.                 {
  44.                     index = testString.Length;
  45.                 }
  46.             }
  47.  
  48.             string[] final = new string[offset + 1];
  49.             if (offset == 0)
  50.             {
  51.                 final[0] = testString;
  52.             }
  53.             else
  54.             {
  55.                 offset--;
  56.                 final[0] = testString.Substring(0, offsets[0]);
  57.                 for (int i = 0; i < offset; i++)
  58.                 {
  59.                     final[i + 1] = testString.Substring(offsets[i] + split.Length, offsets[i + 1] - offsets[i] - split.Length);
  60.                 }
  61.                 final[offset + 1] = testString.Substring(offsets[offset] + split.Length);
  62.             }
  63.             return final;
  64.         }
  65.  
  66.         public byte[] GetPictureByteArray(string url)
  67.         {
  68.             int count = 0;
  69.             byte[] buffer = new byte[1000000];
  70.             int read, total = 0;
  71.             // create StreamWriters
  72.             StreamWriter imagedata_writer = new StreamWriter("imagedata.txt");
  73.             StreamWriter streamdata_writer = new StreamWriter("streamdata.txt");
  74.  
  75.             Console.WriteLine("Creating HTTP request...");
  76.             HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  77.  
  78.             Console.WriteLine("Waiting for response...");
  79.             WebResponse resp = req.GetResponse();
  80.  
  81.             Console.WriteLine("Get response stream...");
  82.             Stream stream = resp.GetResponseStream();
  83.  
  84.             Console.WriteLine("Receiving data...");
  85.             Console.WriteLine("\nHeaders:" + resp.Headers);
  86.             Console.WriteLine("Reading data...");
  87.             while ((read = stream.Read(buffer, total, 1000)) != 0)
  88.             {
  89.                 total += read;
  90.                 // Limit frames through counter
  91.                 if (count != 200)
  92.                     count++;
  93.                 else
  94.                     break;
  95.             }
  96.  
  97.  
  98.             string sComplBuffer = GetStringFromByte(buffer);
  99.             Console.WriteLine("Writing into streamdata.txt...");
  100.             streamdata_writer.Write(sComplBuffer.Trim());
  101.  
  102.             // Split complete buffer into frames (which are separated by --myboundary)
  103.             string[] Frames = SplitByString(sComplBuffer, "--myboundary\r\n");
  104.             //Frames = SplitByString(Frames[2], "\r\n\r\n");
  105.  
  106.             // Save this one frame with imagedata_writer
  107.             imagedata_writer.Write(Frames[1]);
  108.             buffer = StrToByteArray(Frames[1].Trim());
  109.             Console.WriteLine("Writing into imagedata.txt...");
  110.             imagedata_writer.Flush();
  111.             streamdata_writer.Flush();
  112.             return buffer;
  113.  
  114.         }
  115.  
  116.         static void Main(string[] args)
  117.         {
  118.             Console.WriteLine("Program started.");
  119.             Program progrm = new Program();
  120.             byte[] bytarry = progrm.GetPictureByteArray("http://webcam.mmhk.cz/axis-cgi/mjpg/video.cgi");
  121.             Console.WriteLine("\nSaving image to 'image.jpg'...");
  122.  
  123.             FileStream fstrm = new FileStream("image.jpg", FileMode.Create);
  124.             fstrm.Write(bytarry, 0, bytarry.Length);
  125.             fstrm.Flush();
  126.  
  127.             Console.WriteLine("DONE - Press ENTER to close.");
  128.             Console.ReadLine();
  129.         }
  130.     }
  131. }
  132.  
I am using a public camera to test the MJPG stream. So now is the question: what am I doing wrong?
Jul 10 '08 #1
0 2060

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2916
by: Sandeep | last post by:
Hi all, I am new to the ADODB.Stream I am using following code lRecordset.Open "Select * from <some table-name>" 'this query return more than 1000 records dim lstream as new ADODB.stream 'assigning the recordset data to the stream lrecordset.save lstream lStream.Position = 0
6
7358
by: Yechezkal Gutfreund | last post by:
I have been using the following code (successfully) to read Xml formated text packets from a TCP stream. The output from the server stream consists of a sequence of well formed Xml documents written to the output stream. We are willing to pay $ to any expert (e.g. MVP) consultant who has to time to help us track down this problem. (we will discuss rates if you can prove your expertise, and problem solving approach).
0
3122
by: mario.lat_ | last post by:
Hallo to all, I have write a little script for connecting to cisco router BUT I have a problem: I have to send to router all the commands and then I have to read the output. If I send a command1 and read the output for command1 the script works well, If I sent command1 , I send command2 and then I read output for command1 and command2 it works well. If i send command1 and then I read the output for command1 then send command2 I can't...
3
6774
by: Sir Psycho | last post by:
Hi, For some reason, when i step over this code, it returns the full byte stream im expecting from the server, however when I let it run with no intervention, it only seems to grab a small chunk on the stream. What am I doing wrong? There is more code than this, but this is the problem code.
2
1480
by: Mike P2 | last post by:
I made a Stream-inheriting class that just removes the tabs (actually the 4 spaces VS prefers to use) from the beginning of lines and empty lines. At first I was having trouble with it adding a null character in the middle of the output. I think it was a null character, Firefox displays it as a '?' and the W3C validator says it's a non-sgml character '0'. I changed the code around a bit and now the only problem is that it (on some pages of...
8
3756
by: T Driver | last post by:
Anyone have any idea how I can do the following? I have a connection to an XML file on a site I do not control, getting a string representation of the xml data that I can then feed to my XmlDataSource object (CurrentXMLData): Stream newStream = myWebClient.OpenRead(myStringWebResource); TextReader newReader = new StreamReader(newStream); string newData = newReader.ReadToEnd(); CurrentXMLData.Data = newData;
33
2062
by: john | last post by:
I am reading TC++PL3 and in "21.3.3 Stream State", 4 member functions returning bool are mentioned: template <class Ch, class Tr= char_traits<Ch class basic_ios: public ios_base { public: // ... bool good() const; // next operation might succeed bool eof() const; // end of input seen
3
11529
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I'm creating an application that will read emails from GMail, using the System.Net.Sockets.TcpClient and POP protocol. However, I am having a problem with my SslStream. After I create the TcpClient, I create my SslStream... stream = new System.Net.Security.SslStream(tcpclient.GetStream()...);
1
3413
by: Victor Lin | last post by:
Hi, I'm writting a application using python standard logging system. I encounter some problem with unicode message passed to logging library. I found that unicode message will be messed up by logging handler. piese of StreamHandler: try: self.stream.write(fs % msg) except UnicodeError:
0
9464
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,...
0
10292
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9923
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
6722
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
5368
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
5497
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4031
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
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.