bimbima

Daily life experience of ayurvedic medicines, complementary therapies.

How to pass binary or image file to a web service

Some time it is required to create a web service in which one method can take image or binary file data as a parameter.

So to achieve this we have to format or image or binary data to transferable format over HTTP.

Here i am going to explain how we can do this in asp.net or java web service. I am taking example of asp.net.

To do this simple use Convert.ToBas64String() and and Convert.FromBase64String() methods. In Client change binary/ image data to byte array and then change it to Base64 string and in web service change base64 string to byte array and save it or use it as you want.

 

Web service code

[WebMethod]

        public bool addImage(string fileName, string data)

        {

            byte [] bytes = Convert.FromBase64String(data);

            MemoryStream ms = new MemoryStream(bytes);

            Image img = System.Drawing.Image.FromStream(ms);

      img.Save(@"c:\temp\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

 

            return true;

        }

 

 

Client Code Snippet.

 

public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient();

            Bitmap bmp = new Bitmap("d:\\temp\\DSC04618.jpg");

            MemoryStream mstream = new MemoryStream();

            bmp.Save(mstream, ImageFormat.Jpeg);

            byte []bytes = new byte[mstream.Length];

            mstream.Position = 0; 

            mstream.Read(bytes, 0, (int)mstream.Length);

            client.addImage("DSC04618.jpg",Convert.ToBase64String(bytes));

        }

    }