我正在开发一个Android应用程序,它应该将图像发送到我的ASP.NET Web服务,其中图像将保存为文件。我已经看到了几种方法来实现这一点,我选择了这个:将图像转换为字节数组 - >将字节数组转换为字符串 - >使用KSOAP2将字符串发送到Web服务 - >在Web服务接收字符串 - >将其转换为字节数组 - > 将其另存为图片:
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);
然后我将strBase64发送到Web服务。 在Web服务中,我有这个:
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";
}
我在行:Image returnImage = Image.FromStream(ms);
这是我得到的错误:
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
由于
答案 0 :(得分:5)
看起来像是从字符串到图像的转换。此外,您不会处理会泄漏内存的流。
请改为尝试:
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;
}
}