图片的直接存储,数据库的轻量管理,Access 在小型项目里其实还蛮有用的。
Access 的OLE 对象
字段,挺适合拿来存二进制图片的,不用再折腾 FTP 上传那些事,直接用 VBA 搞定就行。写个小函数,把本地图片读成字节数组,一转就能存进数据库,简单又高效。
比如下面这段代码,InsertImageIntoDatabase
负责插图,GetFileBytes
是核心读取逻辑:
Public Sub InsertImageIntoDatabase(filePath As String, db As DAO.Database, tableName As String, imageFieldName As String)
Dim imageData() As Byte
imageData = GetFileBytes(filePath)
With db.TableDefs(tableName).Fields(imageFieldName)
.Value = imageData
.Update
End With
End Sub
Private Function GetFileBytes(filePath As String) As Byte()
Open filePath For Binary Access Read As #1
Dim fileSize As Long
fileSize = LOF(1)
ReDim fileBytes(fileSize - 1)
Get #1, , fileBytes
Close #1
GetFileBytes = fileBytes
End Function
看着多,其实思路挺清晰:读取、转二进制、插入字段,搞定。展示图片也一样,用 OLE 控件指向字段就能显示,挺方便的。
啦,Access 毕竟是轻量级,图片多了之后体积会涨得飞快,性能也受点影响。如果你项目是单机用、图片量也不大,那还挺适合用这种方式,代码写得也舒服。
想拓展下思路,可以看看这些相关文章:ACCESS 数据库二进制图片存储方案、SQL Server 图片存储,思路都差不多,看哪种更贴合你需求。