我想在 sqlite 数据库中以 xamarin 形式存储图片路径,以用于跨平台应用程序。如何存储图像的路径?
答案 0 :(得分:2)
以下是我在sqlite中保存图像所做的工作。我在成功保存图像时返回图像的路径,您可以根据需要更改它。这里图像以字节数组的形式存储。
链接到我的博文:Cross platform utility to save image in sqlite.
Comman界面:
public interface IFileUtility
{
/// <summary>
/// Use to save file in device specific folders
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileStream"></param>
/// <returns></returns>
string SaveFile(string fileName,byte[] fileStream);
/// <summary>
/// Used to delete the existing file directory, before syncing the file again.
/// </summary>
void DeleteDirectory();
}
Android特定代码:
public class FileUtility : IFileUtility
{
public string SaveFile(string fileName,byte[] imageStream)
{
string path = null;
string imageFolderPath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), "ProductImages");
//Check if the folder exist or not
if (!System.IO.Directory.Exists(imageFolderPath))
{
System.IO.Directory.CreateDirectory(imageFolderPath);
}
string imagefilePath = System.IO.Path.Combine(imageFolderPath, fileName);
//Try to write the file bytes to the specified location.
try
{
System.IO.File.WriteAllBytes(imagefilePath, imageStream);
path = imagefilePath;
}
catch (System.Exception e)
{
throw e;
}
return path;
}
public void DeleteDirectory()
{
string imageFolderPath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), "ProductImages");
if (System.IO.Directory.Exists(imageFolderPath))
{
System.IO.Directory.Delete(imageFolderPath,true);
}
}
}
iOS特定代码:
public class FileUtility : IFileUtility
{
public string SaveFile(string fileName,byte[] fileStream)
{
string path = null;
string imageFolderPath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), "ProductImages");
//Check if the folder exist or not
if (!System.IO.Directory.Exists(imageFolderPath))
{
System.IO.Directory.CreateDirectory(imageFolderPath);
}
string imagefilePath = System.IO.Path.Combine(imageFolderPath, fileName);
//Try to write the file bytes to the specified location.
try
{
System.IO.File.WriteAllBytes(imagefilePath, fileStream);
path = imagefilePath;
}
catch (System.Exception e)
{
throw e;
}
return path;
}
public void DeleteDirectory()
{
string imageFolderPath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), "ProductImages");
if (System.IO.Directory.Exists(imageFolderPath))
{
System.IO.Directory.Delete(imageFolderPath,true);
}
}
}
答案 1 :(得分:-1)