C# bitmap保存到缓存,取出数据bitmap数据无效【解决方法】

如果遇到了在将 Bitmap 保存到缓存后,从缓存中取出数据时 Bitmap 数据无效的问题,这通常是因为在将图像数据存入缓存时,数据没有被正确地序列化或者在从缓存读取数据时没有正确地反序列化。在处理 Bitmap 对象时,一个常见的做法是将其转换为一个字节数组,然后存储这个字节数组,因为直接存储 Bitmap 对象可能会导致一些序列化和反序列化的问题。

下面展示如何将 Bitmap 转换为字节数组,并将其保存到内存缓存中,然后再从缓存中读取并恢复为 Bitmap:
1、将 Bitmap 转换为字节数组

csharp 复制代码
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public static byte[] ConvertBitmapToByteArray(System.Drawing.Bitmap bitmap)
{
    if (bitmap == null)
        throw new ArgumentNullException("bitmap");

    using (MemoryStream memoryStream = new MemoryStream())
    {
        bitmap.Save(memoryStream, ImageFormat.Png); // 使用PNG格式保存图像
        return memoryStream.ToArray();
    }
}

2、将字节数组转换回 Bitmap

csharp 复制代码
public static Bitmap ConvertByteArrayToBitmap(byte[] byteArray)
{
    if (byteArray == null)
        throw new ArgumentNullException("byteArray");

    using (MemoryStream memoryStream = new MemoryStream(byteArray))
    {
        return new Bitmap(memoryStream);
    }
}

3、示例使用内存缓存存储和读取 Bitmap

这里以 System.Runtime.Caching.MemoryCache 为例来展示如何使用缓存。首先,你需要添加对 System.Runtime.Caching 的引用。

csharp 复制代码
using System.Runtime.Caching;

public void SaveBitmapToCache(string cacheKey, Bitmap bitmap)
{
    MemoryCache memoryCache = MemoryCache.Default;
    byte[] bitmapBytes = ConvertBitmapToByteArray(bitmap);
    memoryCache.Set(cacheKey, bitmapBytes, DateTimeOffset.UtcNow.AddMinutes(5)); // 缓存5分钟
}

public Bitmap GetBitmapFromCache(string cacheKey)
{
    MemoryCache memoryCache = MemoryCache.Default;
    byte[] bitmapBytes = memoryCache.Get(cacheKey) as byte[];

    if (bitmapBytes == null)
    {
        return null;
    }

    return ConvertByteArrayToBitmap(bitmapBytes);
}

注意事项

  1. 在将 Bitmap 保存到缓存时,我们首先将其转换为字节数组。这样做的好处是可以避免直接序列化 Bitmap 对象可能遇到的问题。
  2. 在从缓存中读取数据时,我们将字节数组转换回 Bitmap。这确保了无论 Bitmap 在缓存中存储了多久,都能够正确地恢复。
  3. 使用 MemoryStream 在转换过程中作为中介,确保了数据的完整性和正确性。 设置缓存的过期时间可以防止缓存无限制增长。

通过上述步骤,你可以安全地将 Bitmap 对象保存到缓存中,并在需要时正确地从缓存中读取和恢复 Bitmap 数据。

相关推荐
大飞pkz31 分钟前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
-Xie-41 分钟前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存
七夜zippoe1 小时前
缓存与数据库一致性实战手册:从故障修复到架构演进
数据库·缓存·架构
weixin_456904271 小时前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
唐青枫2 小时前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
MarkHard12310 小时前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
未来之窗软件服务12 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
心想事成的幸运大王12 小时前
Redis的过期策略
数据库·redis·缓存
1uther12 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间13 小时前
Office转PDF转换器v1.0.py
开发语言·pdf·c#