2016-06-08 47 views
0

我想編輯FTP服務器上的圖像。 我用SSH.net這裏是我的代碼:通過MemoryStream編輯圖像(來自FTP)

using (var client = new SftpClient(ftpUploadPath, ftpPort, ftpUser, ftpPassword)) 
{ 
    client.Connect(); 
    using (var stream = new MemoryStream()) 
    { 
     client.DownloadFile(fileName, stream); 
     using (var img = Image.FromStream(stream, true)) 
     { 
      img.RotateFlip(RotateFlipType.Rotate90FlipNone); 
      img.Save(stream, ImageFormat.Jpeg); 
      client.UploadFile(stream, fileName); 
     } 
    } 
} 

一切都是正確的,直到「client.UploadFile」,它由一個0字節的圖像刪除FTP服務器上的圖像。 FTP服務器上的圖像是.jpg。 我已經在FileStream中使用了「client.UploadFile」,它工作正常。但在這種情況下,我不想將文件保存在我的IIS服務器上,修改它然後將其上傳到FTP服務器... 任何想法?

+0

重置該流爲0,保存它 – noelicus

+1

後...並保存它也,如閱讀前後它將在最後的形象。無論如何,最好創建一個新的流。 –

+0

非常感謝你們兩位!將流位置設置爲0允許我保存圖片但不旋轉。通過一個新的Stream保存它給了我第一個問題。但是,兩者都做了這項工作:) – Gun

回答

1
 img.Save(stream, ImageFormat.Jpeg); 

     stream.Position = 0; // Reset the stream to the beginning before switching to reading it 

     client.UploadFile(stream, fileName); 
0

正如我前面所說,由於noelicus &托爾斯滕,這裏是解決方案:

using (var client = new SftpClient(ftpUploadPath, ftpPort, ftpUser, ftpPassword)) 
{ 
    client.Connect(); 
    using (var stream = new MemoryStream()) 
    { 
     client.DownloadFile(fileName, stream); 
     using (var img = Image.FromStream(stream, true)) 
     { 
      img.RotateFlip(RotateFlipType.Rotate90FlipNone); 

      using (var newStream = new MemoryStream()) 
      { 
       img.Save(newStream, ImageFormat.Jpeg); 
       newStream.Position = 0; 
       client.UploadFile(newStream, item); 
      } 
     } 
    } 
}