VB.net(C#同理)使用 ServiceStack.Redis 二进制存储、读取图像

搜索了一下,网上似乎没有相关的内容,于是把自己探索的经验写一下。

'安装提示:首先需要把当前的目标框架设置为.Net Framwork 4.5。
'使用Nuget安装servicestack.redis,选择5.0版本



Public Class RedisHelper
    Private redisClient As ServiceStack.Redis.RedisClient

    Public Sub New(redisHost As String)
        redisClient = New ServiceStack.Redis.RedisClient(redisHost, 6379)
    End Sub

    ' 保存图像到 Redis 作为 BitMap
    Public Sub SaveImageToRedis(key As String, imagePath As String)
        Dim imageBytes As Byte() = File.ReadAllBytes(imagePath)
        redisClient.Set(key, imageBytes) ' 直接存储字节数组
    End Sub

    Public Function LoadImageFromRedis(key As String) As Drawing.Image
        Dim imageBytes As Byte() = redisClient.GetBytes(key) ' 获取字节数组
        If imageBytes IsNot Nothing Then
            Dim image As Image = ByteArrayToImage(imageBytes)
            Return image
        End If
        Return Nothing
    End Function

    Public Sub LoadImageToPictureBoxFromRedis(key As String, pictureBox As PictureBox)
        pictureBox.Image = LoadImageFromRedis(key)
    End Sub

    ' 从字节数组创建图像
    Private Function ByteArrayToImage(imageBytes As Byte()) As Image
        Using ms As New MemoryStream(imageBytes)
            Return Image.FromStream(ms)
        End Using
    End Function
End Class

 

调用的话参考:

        Dim redisHelper = New RedisHelper("192.168.1.11") ' 替换为你的 Redis 服务器地址
        ' 将图像数据保存到 Redis
        redisHelper.SaveImageToRedis("jpg", imagePath)'自己设置

        '...

        ' 从 Redis 读取图像并显示在 PictureBox 中
        redisHelper.LoadImageToPictureBoxFromRedis("jpg", pictureBox)'自己设置
    End Sub

 

 
posted @ 2024-09-26 16:56  zzgreg  阅读(14)  评论(0编辑  收藏  举报