I created local server, that should get image files as binary data and save them back as images in hard drive.
Socket mySocket = myListener.AcceptSocket();
#region Connection Check
if (mySocket.Connected)
{
============
/* Some Code For Displaying Information*/
============
byte[] data = new byte[mySocket.ReceiveBufferSize];
int i = mySocket.Receive(data, data.Length, 0);
byteArrayToImage(data);
mySocket.Close();
}
byteArrayToImage method Converts byte Array to Image file and saves on hard drive, here's the code
public void byteArrayToImage(Byte[] data)
{
MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);
img.Save(#"C:\MyPersonalwebServer\ImageData\img.png", ImageFormat.Png);
}
but I get ArgumentException here: Image img = Image.FromStream(ms)
Here is part of data array: http://s43.radikal.ru/i101/1403/78/1913ab884790.png
Any ideas how to fix it?
Thanks in advance.
The following code works for me:
var buffer = new byte[256];
FileStream fs = new FileStream(#"D:\test.png", FileMode.Open);
var ms = new MemoryStream();
int readCtr;
while ((readCtr = fs.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, readCtr);
}
Image img = Image.FromStream(ms);
img.Save(#"D:\test2.png", ImageFormat.Png);
Are you sure that the data you are sending from the client connection is complete/clean?
Make sure the data you are sending from the client isn't appending null bytes when performing Socket.Send(), or try clean it up server-side by stripping any null bytes from the end of the byte array:
buffer = buffer.Where(x => x != (byte)0).ToArray();
You could also check the size of the image manually against the content received server-side using standard debug practices/console output.
Either way, I dont think your code would be failing if the byte array had valid content.
How can I decode GSM 6.10 (Full-Rate) codec audio byte array on the fly in NAudio? Sources says that wave decoding is processed at one time and I can't process several bytes of wave (fix me if I'm wrong).
My situation is that I receive bytes array of GSM 6.10 audio from the server, array size can be specified, but how can i decode it and write to the device?
Edit:
What am I doing wrong?
According to Mark's solution this should work but all I hear is distorted sounds:
WaveOut waveO = new WaveOut();
BufferedWaveProvider waveP = new BufferedWaveProvider(new WaveFormat(8000, 16, 1));
waveO.Init(waveP);
waveO.Play();
INetworkChatCodec cod = new Gsm610ChatCodec();
new Thread(delegate()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.nch.com.au/acm/8kgsm.wav");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream resStream = response.GetResponseStream())
{
if (resStream.CanRead)
{
byte[] buf = new byte[65];
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
byte[] decoded = cod.Decode(buf, 0, count);
waveP.AddSamples(decoded, 0, decoded.Length);
Thread.Sleep(50);
}
}
while (count > 0);
}
}
}).Start();
You can do this with the AcmStream class, passing in Gsm610WaveFormat as the source format and 8kHz 16 bit mono as the output format. The network chat demo in the NAudio source code shows this in action to decode on the fly.
I've been struggling with this and can't find a reason why my code is failing to properly read from a TCP server I've also written. I'm using the TcpClient class and its GetStream() method but something is not working as expected. Either the operation blocks indefinitely (the last read operation doesn't timeout as expected), or the data is cropped (for some reason a Read operation returns 0 and exits the loop, perhaps the server is not responding fast enough). These are three attempts at implementing this function:
// this will break from the loop without getting the entire 4804 bytes from the server
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytes = stm.Read(resp, 0, resp.Length);
while (bytes > 0)
{
memStream.Write(resp, 0, bytes);
bytes = 0;
if (stm.DataAvailable)
bytes = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
// this will block forever. It reads everything but freezes when data is exhausted
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytes = stm.Read(resp, 0, resp.Length);
while (bytes > 0)
{
memStream.Write(resp, 0, bytes);
bytes = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
// inserting a sleep inside the loop will make everything work perfectly
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytes = stm.Read(resp, 0, resp.Length);
while (bytes > 0)
{
memStream.Write(resp, 0, bytes);
Thread.Sleep(20);
bytes = 0;
if (stm.DataAvailable)
bytes = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
The last one "works", but it certainly looks ugly to put a hard-coded sleep inside the loop considering that sockets already support read timeouts! Do I need to setup some property(ies) on the TcpClient of the NetworkStream? Does the problem resides in the server? The server don't close the connections, it is up to the client to do so. The above is also running inside the UI thread context (test program), maybe it has something to do with that...
Does someone know how to properly use NetworkStream.Read to read data until no more data is available? I guess what I'm wishing for is something like the old Win32 winsock timeout properties... ReadTimeout, etc. It tries to read until the timeout is reached, and then return 0... But it sometimes seem to return 0 when data should be available (or on the way.. can Read return 0 if is available?) and it then blocks indefinitely on the last read when data is not available...
Yes, I'm at a loss!
Networking code is notoriously difficult to write, test and debug.
You often have lots of things to consider such as:
what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.
are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive
how does congestion in the real world which causes delays in the stream affect your reading/writing logic
If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).
Here are several different ways to handle the exchange:
have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"
use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"
use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.
have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)
Each approach has its pros and cons for "correctness".
The code below uses the "timeout" method, as that seems to be the one you want.
See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
// Set a 250 millisecond timeout for reading (instead of Infinite the default)
stm.ReadTimeout = 250;
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytesread = stm.Read(resp, 0, resp.Length);
while (bytesread > 0)
{
memStream.Write(resp, 0, bytesread);
bytesread = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);
Setting the underlying socket ReceiveTimeout property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
As per your requirement, Thread.Sleep is perfectly fine to use because you are not sure when the data will be available so you might need to wait for the data to become available. I have slightly changed the logic of your function this might help you little further.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytes = 0;
do
{
bytes = 0;
while (!stm.DataAvailable)
Thread.Sleep(20); // some delay
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
Hope this helps!
I want to preload a lot of images when my app starts up, sort of a once off thing.
I have an Image class that contains the Url of its image stored in the cloud as blob storage (this address is a https address BTW)
I want to download the image bytes from the cloud, store them on the object, then when it comes time to show the image, load the image from its bytes.
I have all the code for this, but I keep getting the exception:
No imaging component suitable to complete this operation was found.
Here is my code: EDIT UPDATED WITH A FIX
//Loaded on start-up
private static void LoadImageBytes(Image img)
{
var urlUri = new Uri(img.Url);
var request = (HttpWebRequest)WebRequest.CreateDefault(urlUri);
MemoryStream memStream = new MemoryStream();
using (var response = request.GetResponse())
{
var buffer = new byte[4096];
using (var stream = response.GetResponseStream())
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
memStream.Write(buffer, 0, bytesRead);
bytesRead = stream.Read(buffer, 0, buffer.Length);
}
img.ImageBytes = memStream.ToArray();
}
}
}
Then when I want to get the image on the screen I call this:
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
stream.Seek(0, SeekOrigin.Begin);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
But in the EndInit() call I get the exception.
I have done some testing and if I load the file from my local filesystem, I get a different set of bytes to that of the image in the cloud. I assume its something to do with blob storage or https?
And yes I can browse to that image and its not corrupted.
EDIT, fixed now all good
Are you sure this line is correct?
while (stream.Read(buffer, 0, buffer.Length) > 0)
img.ImageBytes = buffer;
img.ImageBytes will hold the last read buffer.
byte[] imageData = null;
long byteSize = 0;
byteSize = _reader.GetBytes(_reader.GetOrdinal(sFieldName), 0, null, 0, 0);
imageData = new byte[byteSize];
long bytesread = 0;
int curpos = 0, chunkSize = 500;
while (bytesread < byteSize)
{
// chunkSize is an arbitrary application defined value
bytesread += _reader.GetBytes(_reader.GetOrdinal(sFieldName), curpos, imageData, curpos, chunkSize);
curpos += chunkSize;
}
byte[] imgData = imageData;
MemoryStream ms = new MemoryStream(imgData);
Image oImage = Image.FromStream((Stream)ms);
return oImage;
Code creates problem when "Image oImage = Image.FromStream((Stream)ms);" line executes.....This line shows "Parameter is not valid" message .......Why it occurs? Help me. I want to retrieve image from database ....I work on C# window vs05 .....Can any one help me? byte[] contain value. All works well, just problem occurs when this line executes.
A simple if statement should solve your problem before creating the memory stream
if (imageData.Length != 0)
{
MemoryStream ms = new MemoryStream(imageData);
Image oImage = Image.FromStream((Stream)ms);
return oImage;
}
return null;
I can't really spot any errors in this code (other than the MemoryStream not being disposed, and that it's not necessary to cast it to Stream when passing it to the Image.FromStream method; but those should not cause your error). I would do the following in order to try to find the error:
Write the byte data to a file and try to open the image in a graphics program (to verify that the byte data does indeed represent a valid image). My guess is that this would fail.
Check the code that writes the data to the database (perhaps perform the same trick as in the previous point; write it to a file and try to open the file)