VB.net(C#同理)使用 ServiceStack.Redis 二進位制儲存、讀取影像

zzgreg發表於2024-09-26

搜尋了一下,網上似乎沒有相關的內容,於是把自己探索的經驗寫一下。

'安裝提示:首先需要把當前的目標框架設定為.Net Framwork 4.5。
'方法一:複製ebay訂單裡的DLL\ServiceStack.Redis(整個資料夾),自行新增引用(4個dll)
'方法二:使用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

相關文章