I'm developing an Android App that should send an image to my ASP.NET Web Service where the image will be saved as a file. I've seen a couple of ways to do this and I went for this one: convert the image to a byte array -> convert the byte array to a string -> send the string to the web service using KSOAP2 -> receive the String at the Web Service -> convert it to a byte array -> Save it as an image:
IVtest = (ImageView)findViewById(R.id.carticon);
BitmapDrawable drawable = (BitmapDrawable) IVtest.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
ImageView image=new ImageView(this);
image.setImageBitmap(bmp);
String strBase64 = Base64.encode(data);
Then I send strBase64 to the web service. In the Web Service I have this:
public Image ConvertToImage(byte[] image)
{
MemoryStream ms = new MemoryStream(image);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
[WebMethod]
public String UploadImage(String image, String name)
{
byte[] image_byte = Encoding.Unicode.GetBytes(image);
Image convertedImage = ConvertToImage(image_byte);
try {
convertedImage.Save(Server.MapPath("generated_image.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
} catch (Exception e) {
return e.Message;
}
return "Success";
}
I get an error at this line: Image returnImage = Image.FromStream(ms);
This is the error I get:
SoapFault - faultcode: 'soap:Server' faultstring: 'System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentException: Parameter is not valid.
at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
at System.Drawing.Image.FromStream(Stream stream)
at Service.ConvertToImage(Byte[] image) in e:\FTP\nvm\Service.asmx:line 1366
at Service.UploadImage(String image, String name) in e:\FTP\nvm\Service.asmx:line 1374
--- End of inner exception stack trace ---' faultactor: 'null' detail: org.kxml2.kdom.Node@437bf7b0
Thanks
Seems like there is something iffy with your conversion from string to image. Also you are not disposing your stream which will leak memory.
Try this instead:
private Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
using (var ms = new MemoryStream(imageBytes, 0,
imageBytes.Length))
{
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
}