简体   繁体   中英

xamarin.forms save file/image

coding xamarin form project and also using pcl storage. have problem with saving image or file on device all examples i found show how to save stream of byte array into file but non of them show how to turn convert image into usable format for saving.

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

In other words looking for code to save image/file on device from url.

Tried ffimageloading since it contain converter to byte[], but always get error:"Object reference not set to an instance of an object." for GetImageAsJpgAsync and GetImageAsPngAsync method. problem might be that image isn't fully loaded. but finish event and finish command never get called even trough image is fully loaded on screen and bound to cachedImage.

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


var image = await cachedImage.GetImageAsJpgAsync();

With FFImageLoading (I noticed you use it):

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

If you want to get original file location, use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM