我已经将resize_to_fill缩小到[1,1]大小,从而将图像缩小为包含基本上整个图像的平均颜色的单个像素(假设图像在高度和宽度之间没有很大的差异,当然) . 现在我试图以十六进制格式检索这
现在我试图以十六进制格式检索这个单个像素的颜色.
从终端窗口我可以像这样运行convert命令:
convert image.png txt: # ImageMagick pixel enumeration: 1,1,255,rgb 0,0: (154,135,116) #9A8774 rgb(154,135,116)
但是我不确定如何在图像所属的模型的before_save部分中从应用程序内部运行此命令.
使用carrierwave上传和附加图像
到目前为止,我已检索到图像:
image = MiniMagick::Image.read(File.open(self.image.path))
但我不太确定如何从这里开始.
您可以添加像这样的pixel_at方法:module MiniMagick class Image def pixel_at(x, y) case run_command("convert", "#{escaped_path}[1x1+#{x}+#{y}]", "-depth 8", "txt:").split("\n")[1] when /^0,0:.*(#[\da-fA-F]{6}).*$/ then $1 else nil end end end end
然后像这样使用它:
i = MiniMagick::Image.open("/path/to/image.png") puts i.pixel_at(100, 100)
输出:
#34555B