C# 本地图片缓存器ImageFileCache (www.csframework.com)

  C# 本地图片缓存器ImageFileCache (www.csframework.com)

C# 本地图片缓存器ImageFileCache (www.csframework.com)


C# Code:

/// <summary>
/// C# 本地图片缓存器(www.csframework.com)
/// </summary>
public class ImageFileCache
{
  
//考虑异步应用,加锁
  
private object _Locker = new object();
  
  
//图片根目录
  
private string _baseFolder = "";
  
  
//图片数据库
  
private DataTable _Data;
  
  
/// <summary>
  
/// 构造器
  
/// </summary>
  
public ImageFileCache(string baseFolder = "")
  {
    
//默认为应用程序目录下
    
if (String.IsNullOrWhiteSpace(baseFolder))
    baseFolder
= Path.Combine(Application.StartupPath, "ImageCache");
    
    _baseFolder
= baseFolder;
    
    
if (!Directory.Exists(baseFolder))
    Directory.CreateDirectory(baseFolder);
    
    
//加载数据库
    
_Data = ReadDatabase();
  }
  
  
#region Instance
  
  
static ImageFileCache _Instance = null;
  
  
public static ImageFileCache Instance
  {
    
get
    {
      
if (_Instance == null) _Instance = new ImageFileCache();
      
return _Instance;
    }
  }
  
  
#endregion;
  
  
internal bool Exists(ImageBuckleName buckle, string url)
  {
    url
= ToMD5(url);
    
    
lock (_Locker)
    {
      
return _Data.Select($"buckle='{buckle.ToString()}' AND url='{url}'").Length > 0;
    }
  }
  
  
/// <summary>
  
/// 数据库文件路径
  
/// </summary>
  
private string dbFile { get { return Path.Combine(_baseFolder, "cache_files.db"); } }
  
  
/// <summary>
  
/// 加载数据库
  
/// </summary>
  
/// <returns></returns>
  
private DataTable ReadDatabase()
  {
    
lock (_Locker)
    {
      
string path = this.dbFile;
      
      
if (File.Exists(path))
      {
        _Data
= GetFileTable();
        _Data.ReadXml(path);
        
return _Data;
      }
      
else
      {
        _Data
= GetFileTable();
        
return _Data;
      }
    }
  }
  
  
/// <summary>
  
/// 保存数据库
  
/// </summary>
  
public void Save()
  {
    
lock (_Locker)
    {
      _Data.WriteXml(
this.dbFile, true);
    }
  }
  
  
/// <summary>
  
/// 获取图片
  
/// </summary>
  
/// <param name="buckle"></param>
  
/// <param name="url"></param>
  
/// <returns></returns>
  
public Bitmap GetImage(ImageBuckleName buckle, string url)
  {
    url
= ToMD5(url);
    
    
lock (_Locker)
    {
      
var rows = _Data.Select($"buckle='{buckle.ToString()}' AND url='{url}'");
      
      
if (rows.Length > 0)
      {
        
string file = Path.Combine(_baseFolder, rows[0]["name"].ToString());
        
        
//C#加载图片文件,不占用文件句柄方式。
        
byte[] bs = File.ReadAllBytes(file);
        MemoryStream ms
= new MemoryStream(bs);
        
return new Bitmap(Image.FromStream(ms));
      }
      
else
      {
        
return null;
      }
    }
  }
  
  
/// <summary>
  
/// 添加图片
  
/// </summary>
  
/// <param name="url"></param>
  
/// <param name="img"></param>
  
/// <param name="buckle"></param>
  
public void AddImage(string url, Image img, ImageBuckleName buckle)
  {
    
lock (_Locker)
    {
      
string md5 = ToMD5(url);
      
      
string dir = Path.Combine(_baseFolder, buckle.ToString());
      
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
      
      
string ext = Path.GetExtension(url);
      
string fileName = md5 + ext;
      fileName
= buckle.ToString() + @"\" + fileName;
      
      
string file = Path.Combine(_baseFolder, fileName);
      img.Save(file);
      
      
if (File.Exists(file))
      {
        DataRow row
= _Data.Rows.Add();
        row[
"buckle"] = buckle.ToString();
        row[
"name"] = fileName;
        row[
"url"] = md5;//将url转化为md5
        
row["time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        _Data.AcceptChanges();
      }
    }
  }
  
  
private DataTable GetFileTable()
  {
    DataTable dt
= new DataTable("file");
    dt.Columns.Add(
"isid", typeof(int));
    dt.Columns.Add(
"buckle", typeof(String));
    dt.Columns.Add(
"url", typeof(String));
    dt.Columns.Add(
"name", typeof(String));
    dt.Columns.Add(
"time", typeof(String));
    
return dt;
  }
  
  
/// <summary>
  
/// MD5加密,不可逆
  
/// </summary>
  
/// <param name="clearText">明文字符串</param>
  
/// <returns></returns>
  
private string ToMD5(string clearText)
  {
    MD5CryptoServiceProvider md5
= new MD5CryptoServiceProvider();
    
byte[] encryptedBytes = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(clearText));
    StringBuilder sb
= new StringBuilder();
    
for (int i = 0; i < encryptedBytes.Length; i++)
    {
      sb.AppendFormat(
"{0:x2}", encryptedBytes[i]);
    }
    
return sb.ToString().ToLower();
  }
}


//来源:C/S框架网 | www.csframework.com | QQ:23404761




C# Code:


/// <summary>
/// 图片存储子目录(可自定义)
/// </summary>
public enum ImageBuckleName
{
  large_images,
  small_images
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



缓存图片文件目录结构,以及图片数据库文件:


贴图图片-imagelocalcache




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务



版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
发表评论

评论内容
昵称:
关联文章

C# 本地图片缓存ImageFileCache (www.csframework.com)
C#数据库本地缓存技术(Database local cache)
C/S架构快速开发框架SQL并发测试压力测试 | www.csframework.com
CS开发框架版本介绍(www.csframework.com)
C/S系统快速开发框架核心竞争力报告|www.CSFramework.com
C/S框架日志管理管理(LogUserOperate)/本地日志(LogLocalException)/数据库日志(LogDB)
众里寻她千百度,蓦然回首,C/S框架就在www.csframework.com...
阿里云ECS服务器上IIS部署多个Web网站详解|www.CSframework.com
原创:C#源码 GridMovetor按回车自动跳到下一列或自动新增记录(www.csframework.com)
C#代码的Excel读取(不需要Office Excel Com组件)
C#获取本地的IP地址
C# Dev GridView表格的CustomUnboundColumnData事件异步加载图片类AsynDownImage
CSFramework.COM C/S架构开发框架成功案例汇总
C# INI本地文件读写工具类IniFileTool.cs
C#切割图片自动填充工具栏按钮图片
CSFramework.WebApi令牌管理(Token Provider)实现添加、删除、刷新令牌过期控制
C#微信支付完成前端回调通知notify_url完整版源码|CSframework.com原创文章
C#使用分词算法从文本字符串中抽取关键词模拟百度搜索|CSFramework.COM巨献
CSFramework.COM原创:全球国家名称列表国旗图标库导入程序(C#+VS2015)
开发应用-观察者模式之C#实现缓存数据更新