0

i have a wcf rest which is recieving an image from andriod device and save into public shared folder.

everything is working well but while saving the image file(actual image size is 15kb) into my shared folder it is saving with 489kb.

Any image file is saving with 489kb only. I found the problem why it is saving like this..

this is my code..

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "UploadImage")]
public string RecieveImage(Stream ImageStream)
{
    try
    {
        byte[] buffer = new byte[500000];
        ImageStream.Read(buffer, 0, 500000);
        FileStream f = new FileStream(@"c:\desktop\wcfUploadImage.jpeg", FileMode.OpenOrCreate);               
        f.Write(buffer, 0, buffer.Length);
        f.Close();
        f.Dispose();
    }
    catch (Exception ex)
    {
        throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.BadRequest);
    }

    return "Successsfully recieved.";
}

Because of byte[500000] only i am saving the image with 489kb. i am getting an error if i replaced 500000 with ImageStream.length.

What is the correct way to save the image with actual size?

AgentFire
  • 8,944
  • 8
  • 43
  • 90
Balu
  • 39
  • 7
  • You only read 500Kb... you need to read until `Read` method returns 0. And indeed you have to use `ImageStream.length` to read the whole file, what is the error when using it? Try to cast it to `int` as it returns a `long`. – Yann39 Sep 16 '13 at 09:11

1 Answers1

0

Stream's Read method returns the number of bytes it has actually read as Int32. Use that value.

Note that if it returns exact number of bytes you asked for (eg. 500000), than it is highly likely that you need to read the stream again: there is still unread data.

AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • thank you.. i did not get "Note that if it returns exactly you max-asked for it (eg. 500000), than it is highlu licked that you need to read the stream again: there is still unread data." point. Can you explain it breifly – Balu Sep 16 '13 at 09:33
  • @Balu sorry for my english, I have fixed grammar errors. What I mean is that you should `Read` data until the return number of bytes is zero. – AgentFire Sep 16 '13 at 13:01
  • its ok Agenfire.. :) Here i have posted one more question please recify dude.... http://stackoverflow.com/questions/18827088/unable-to-upload-an-image-with-parameters-to-wcf-rest-service or http://www.codeproject.com/Questions/654219/Unable-to-upload-an-image-with-parameters-to-wcf-r or http://social.msdn.microsoft.com/Forums/vstudio/en-US/7a43ae7f-12f7-430c-b9df-9994ba973bca/unable-to-upload-an-image-with-parameters-to-wcf-rest-service – Balu Sep 16 '13 at 13:11