PCL将图像文件保存到本地文件系统

时间:2014-03-19 07:47:56

标签: cross-platform xamarin storage portable-class-library

我正在寻找一种方法,使用我的核心项目Windows PhoneXamarin.Android和{{1}中的 PCL存储插件,将图像文件存储在我的本地文件系统中}。 但是,插件只提供了编写Text的方法。什么关于字节。 有没有办法保存字节数组?

3 个答案:

答案 0 :(得分:22)

这样的事情怎么样:

IFile file = await FileSystem.Current.GetFileFromPathAsync(fs.filepath);
byte[] buffer = new byte[100];
using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
    stream.Write(buffer, 0, 100);
}

修改:部分代码来自http://pclstorage.codeplex.com/

IFile file = await folder.CreateFileAsync("myfile.abc", CreationCollisionOption.ReplaceExisting);

一旦你获得了IFile对象,你就应该以同样的方式使用它:

IFile file = await folder.CreateFileAsync("myfile.abc", CreationCollisionOption.ReplaceExisting);
byte[] buffer = new byte[100];
using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
    stream.Write(buffer, 0, 100);
}

答案 1 :(得分:3)

您还可以查看Paul Betts'用于跨平台图像加载/保存的Splat库。

https://github.com/paulcbetts/splat

答案 2 :(得分:0)

要拍照并将日期和时间存储在上面,我使用了以下组合:

  1. Plugin.Media
  2. Plugin.Media.Abstractions
  3. PCLStorage
  4. SkiaSharp
  5. 我发现了这个Using SkiaSharp, how to save a SKBitmap ?并将其用作此基础:

    // I get my bitmap from the camera (Plugin.Media allows to pick it from filesystem too)
    var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
    {
        Directory = "MyFolder",
        Name = "MyPic001",
        PhotoSize = PhotoSize.Medium,
        CompressionQuality = 40,
        SaveToAlbum = true
    });
    // If succesfully taken...
    if (file != null)
    {
        // Start using SkiaSharp to write text on it
        var bitmap = SKBitmap.Decode(file.Path);
        var canvas = new SKCanvas(bitmap);
        var font = SKTypeface.FromFamilyName("Arial");
        var brush = new SKPaint
        {
            Typeface = font,
            TextSize = Convert.ToInt64(40),
            IsAntialias = true,
            Color = new SKColor(255, 255, 255, 255)
        };
        // Write on top of the image
        canvas.DrawText(DateTime.Now.ToString("dd/MM/yyyy HH:mm"), 10, 60, brush);
        var imageSK = SKImage.FromBitmap(bitmap);
        // Get rootFolder and FileName from Plugin.Media's file.Path
        string A = file.Path;
        string P = A.Substring(0, A.LastIndexOf("/"));
        string F = A.Substring(A.LastIndexOf("/") + 1, A.Length - (A.LastIndexOf("/") + 1));
        // Start using PCLStorage
        IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync(P);
        IFile myFile = await rootFolder.GetFileAsync(F);
        // Use PCLStorage file opening to create an IO.Stream
        using (Stream s = await myFile.OpenAsync(FileAccess.ReadAndWrite))
        {
            // Use SkiaSharp SKImage and SKData to Save the image+text on file.Path
            SKData d = imageSK.Encode(SKEncodedImageFormat.Jpeg, 40);
            d.SaveTo(s);
        }
    }
    
相关问题