Help us understand the problem. What is going on with this article?

MiniMagick 画像を配列へ、配列を画像へ

準備

  • mini_magickをインストール。
  • レナさんの画像を用意。
test.rb
require "mini_magick"

img0 = MiniMagick::Image.open "lena.png"

画像を配列に

get_pixelメソッドを用いる。

test.rb
pixels = img0.get_pixels

画素を取得

pixels[上からの位置][左からの位置][赤=0, 緑=1, 青=2]のようにする。

# 上から0、左から0の画素を取得
p pixels[0][0] # [223, 135, 121]

# 上から0、左から0の画素で赤を取得
p pixels[0][0][0] # 223

配列を画像に

import_pixelsメソッドを用いる。

import_pixelsメソッドの引数はこんな感じ。

引数 意味 種類
blob バイナリ文字列 String
columns 横の長さ Integer
rows 縦の長さ Integer
depth ビット深度 Integer
map "rgb" or "gray" String
format = "png" フォーマット String

配列をバイナリ文字列に

平坦化(flatten)して、バイナリ(pack("C*"))に。

https://docs.ruby-lang.org/ja/latest/method/Array/i/flatten.html
https://docs.ruby-lang.org/ja/latest/method/Array/i/pack.html

p pixels.flatten.pack "c*"
# "\xDF\x87y\xE1\x89{\xE2\x8A|\xE4\x8C~\xE3\x8B}\xE2\x8A(略
test.rb
img1 = MiniMagick::Image.import_pixels(blob = pixels.flatten.pack("C*"), columns = pixels[0].size, rows = pixels.size, depth = 8, map = "rgb")
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away