ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 处理图像 > 原文: [http://zetcode.com/db/sqliteruimg/](http://zetcode.com/db/sqliteruimg/) 在 SQLite Ruby 教程的这一章中,我们将使用图像文件。 请注意,有些人反对将图像放入数据库。 在这里,我们只展示如何做。 我们不讨论是否将图像保存在数据库中的技术问题。 ```ruby sqlite> CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB); ``` 对于此示例,我们创建一个名为`Images`的新表。 对于图像,我们使用`BLOB`数据类型,代表二进制大对象。 ## 插入图像 在第一个示例中,我们将图像插入 SQLite 数据库。 ```ruby #!/usr/bin/ruby require 'sqlite3' begin fin = File.open "woman.jpg" , "rb" img = fin.read rescue SystemCallError => e puts e ensure fin.close if fin end begin db = SQLite3::Database.open 'test.db' blob = SQLite3::Blob.new img db.execute "INSERT INTO Images VALUES(1, ?)", blob rescue SQLite3::Exception => e puts "Exception occurred" puts e ensure db.close if db end ``` 我们从当前工作目录中读取图像,并将其写入 SQLite `test.db`数据库的`Images`表中。 ```ruby fin = File.open "woman.jpg" , "rb" img = fin.read ``` 我们打开并阅读 JPG 图像。 `read`方法以字符串形式返回数据。 ```ruby blob = SQLite3::Blob.new img ``` 我们创建`SQLite3::Blob`类的实例。 它用于处理二进制数据。 ```ruby db.execute "INSERT INTO Images VALUES(1, ?)", blob ``` 图像被写入数据库。 ## 读取图像 在本节中,我们将执行相反的操作。 我们将从数据库表中读取图像。 ```ruby #!/usr/bin/ruby require 'sqlite3' begin db = SQLite3::Database.open 'test.db' data = db.get_first_value "SELECT Data FROM Images LIMIT 1" f = File.new "woman2.jpg", "wb" f.write data rescue SQLite3::Exception, SystemCallError => e puts "Exception occurred" puts e ensure f.close if f db.close if db end ``` 我们从图像表中读取图像数据,并将其写入另一个文件,我们将其称为`woman2.jpg`。 ```ruby data = db.get_first_value "SELECT Data FROM Images LIMIT 1" ``` 该行从表中选择图像数据。 ```ruby f = File.new "woman2.jpg", "wb" f.write data ``` 我们打开一个新的图像文件,并将检索到的数据写入该文件。 然后我们关闭文件。 SQLite Ruby 教程的这一部分专门用于读取和写入图像。