2017-09-23 244 views
0

編碼xamarin表單項目,也使用pcl存儲。在設備上保存圖像或文件時出現問題我找到的所有示例都顯示如何將字節數組流保存到文件中,但沒有顯示如何將轉換圖像轉換爲可用格式以進行保存。xamarin.forms保存文件/圖像

 var webImage = new Image(); 
     webImage.Source = new UriImageSource 
     { 
      CachingEnabled = false, 
      Uri = new Uri("http://server.com/image.jpg"), 
     }; 
     byte[] image = ????(what i need)????(webImage.Source); 

     // get hold of the file system 
     IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage; 

     // create a file, overwriting any existing file 
     IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); 

     // populate the file with image data 
     using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite)) 
     { 
      stream.Write(image, 0, image.Length); 
     } 

換句話說,尋找代碼來保存設備上的圖像/文件從網址。

嘗試ffimageloading,因爲它包含轉換器到byte [],但總是得到錯誤:「對象引用未設置爲對象的實例。」用於GetImageAsJpgAsync和GetImageAsPngAsync方法。問題可能是圖像未完全加載。但完成事件和完成命令永遠不會被調用,即使槽圖像完全加載在屏幕上並綁定到cachedImage。

var cachedImage = new CachedImage() 
{ 
    Source = "https://something.jpg", 
    FinishCommand = new Command(async() => await TEST()), 
}; 
cachedImage.Finish += CachedImage_Finish; 


var image = await cachedImage.GetImageAsJpgAsync(); 

回答

0
public static async Task<byte[]> DownloadImageAsBytesArray(string imageUrl) 
{ 
    using (var client = new HttpClient 
    { 
     Timeout = TimeSpan.FromSeconds(10) 
    }) 
    { 
     try 
     { 
      using (var response = await client.GetAsync(imageUrl)) 
      { 
       byte[] imageAsBytesArray = null; 
       if (response.StatusCode == System.Net.HttpStatusCode.OK) 
       { 
        imageAsBytesArray = await response.Content.ReadAsByteArrayAsync(); 
       } 

       return imageAsBytesArray; 
      } 
     } 
     catch (Exception e) 
     { 
      return null; 
     } 
    } 
} 
0

隨着FFImageLoading(我注意到您使用它):

await ImageService.Instance.LoadUrl("https://something.jpg").AsJpegStream();

如果你想獲得原始文件的位置,使用此:

await ImageService.Instance.LoadUrl("https://something.jpg").Success((imageInfo) => { //TODO imageInfo.FilePath }).DownloadOnly();