2012-02-22 72 views
5

我正在開發一個Android應用程序,該應用程序應該將圖像發送到我的ASP.NET Web服務,並將圖像保存爲文件。我已經看到了一些方法來做到這一點,我去了這一點:將圖像轉換爲字節數組 - >將字節數組轉換爲字符串 - >使用KSOAP2將字符串發送到Web服務 - >接收字符串在Web服務 - >將其轉換爲字節數組 - > 保存爲圖像:從Android發送圖像到ASP.NET 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 Service我有這樣的:Image returnImage = Image.FromStream(ms);

這是我的錯誤:

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"; 
} 

我在這個得到一個錯誤

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: [email protected] 

感謝

回答

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; 
     } 
    } 
+0

非常感謝,也做了工作。該圖像終於在服務器上:) – ice 2012-02-23 18:59:47

相關問題