<table>
<tr>
<td>hello</td>
<td><img src="xyz.png" width="100" height="100"></td>
</tr>
</table>
我想将这个 xyz.png 以 blob 形式保存到我的数据库中,那么如何以 blob
形式保存图像。
最佳答案
看一下我写的这个简单示例。本质上,我只是使用 id 找到我想要的图像,然后获取它的源。然后,我打开一个临时文件来保存图像的内容,最后,我打开该 src 的 url 并将其写入临时文件。使用临时文件的好处是无需清理。
require 'watir-webdriver'
require 'open-uri'
require 'tempfile'
browser = Watir::Browser.new :firefox
browser.goto("http://www.reddit.com")
img = browser.image(:id, "header-img").src
tempFile = Tempfile.new('tempImage')
open(img, 'rb') do |image|
tempFile.write(image.read)
end
tempFile.rewind
puts tempFile.read ###Make your database call here, simply save this tempFile.read as a blob
tempFile.close
tempFile.unlink # completely deletes the temp file
browser.close
对于这个例子,我只是获取 reddit Logo 并将二进制数据打印到屏幕上。您从未指定您正在使用哪个数据库,所以我不想假设,但您不会执行“放置”,而是在那里进行数据库调用。
关于ruby - 如何使用 watir 将图像保存在 blob 字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16190826/