using System.Text;
using System.Windows.Media.Imaging;
namespace HKW.HKWUtils;
///
/// 工具
///
public static class HKWUtils
{
///
/// 解码像素宽度
///
public const int DecodePixelWidth = 250;
///
/// 解码像素高度
///
public const int DecodePixelHeight = 250;
public static char[] Separator { get; } = new char[] { '_' };
///
/// 载入图片到流
///
/// 图片路径
/// 图片
public static BitmapImage LoadImageToStream(string imagePath)
{
if (string.IsNullOrWhiteSpace(imagePath) || File.Exists(imagePath) is false)
return null;
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
try
{
bitmapImage.StreamSource = new StreamReader(imagePath).BaseStream;
}
finally
{
bitmapImage.EndInit();
}
return bitmapImage;
}
///
/// 载入图片至内存流
///
/// 图片路径
///
public static BitmapImage LoadImageToMemoryStream(string imagePath)
{
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
try
{
var bytes = File.ReadAllBytes(imagePath);
bitmapImage.StreamSource = new MemoryStream(bytes);
bitmapImage.DecodePixelWidth = DecodePixelWidth;
}
finally
{
bitmapImage.EndInit();
}
return bitmapImage;
}
///
/// 载入图片至内存流
///
/// 图片流
///
public static BitmapImage LoadImageToMemoryStream(Stream imageStream)
{
BitmapImage bitmapImage = new();
bitmapImage.BeginInit();
try
{
bitmapImage.StreamSource = imageStream;
bitmapImage.DecodePixelWidth = DecodePixelWidth;
}
finally
{
bitmapImage.EndInit();
}
return bitmapImage;
}
///
/// 获取布尔值
///
/// 值
/// 目标布尔值
/// 为空时布尔值
///
public static bool GetBool(object value, bool boolValue, bool nullValue)
{
if (value is null)
return nullValue;
else if (value is bool b)
return b == boolValue;
else if (bool.TryParse(value.ToString(), out b))
return b == boolValue;
else
return false;
}
///
/// 打开文件
///
/// 文件路径
public static void OpenLink(string filePath)
{
System.Diagnostics.Process
.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true })
?.Close();
}
///
/// 从资源管理器打开文件
///
/// 文件路径
public static void OpenFileInExplorer(string filePath)
{
System.Diagnostics.Process
.Start("Explorer", $"/select,{Path.GetFullPath(filePath)}")
?.Close();
}
///
/// 从文件获取只读流 (用于目标文件被其它进程访问的情况)
///
/// 文件
/// 编码
/// 流读取器
public static StreamReader StreamReaderOnReadOnly(string path, Encoding? encoding = null)
{
encoding ??= Encoding.UTF8;
var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return new StreamReader(fs, encoding);
}
}