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

问题描述 投票:9回答:3

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

cross-platform xamarin storage portable-class-library
3个回答
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);
}

3
投票

您还可以查看Paul Betts的Splat库,以便进行跨平台图像加载/保存。

https://github.com/paulcbetts/splat


0
投票

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

  1. plugin.Media
  2. Plugin.Media.Abstractions
  3. PCLStorage
  4. SkiaSharp

我发现这个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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.