クイックリファレンス

ChunkyPNG チートシート(Ruby PNG画像処理ライブラリ)

純粋な Ruby 実装の PNG 処理ライブラリ ChunkyPNG のクイックリファレンス。画像の読み込み、保存、ピクセル描画、トリミング、幾何図形描画を解説。

· 公開日

ChunkyPNG は、外部の C 拡張や ImageMagick を必要とせずに、PNG 画像の読み書きや編集を行える純粋な Ruby ライブラリです。

画像の読み込み(Loading Images)

require 'chunky_png'

# Load directly from filesystem
image = ChunkyPNG::Image.from_file('input.png')

# Load from binary in-memory blob or IO stream
image = ChunkyPNG::Image.from_blob(File.binread('input.png'))
image = ChunkyPNG::Image.from_io(io_stream)

画像の保存とエクスポート(Saving Images)

# Save to file
image.save('output.png')

# Export to binary string blob
binary_blob = image.to_blob

# Write to stream
File.open('stream.png', 'wb') { |io| image.write(io) }

ピクセル操作と図形描画(Pixel Drawing)

# Set individual pixel RGBA values
image[0, 0] = ChunkyPNG::Color.rgba(255, 0, 0, 128)

# Color constructors
red  = ChunkyPNG::Color.from_hex('#ff0000')
cyan = ChunkyPNG::Color.rgba(0, 255, 255, 255)

# Draw geometric primitives
image.line(10, 10, 100, 10, red)
image.rect(20, 20, 80, 80, red, cyan) # border, fill
image.circle(50, 50, 25, red)

切り抜きと変形操作(Canvas Transforms)

# Crop sub-rectangle: crop(x, y, width, height)
cropped = image.crop(10, 10, 200, 200)

# Flipping and rotation
transformed = image.flip_horizontally.rotate_right
flipped_v   = image.flip_vertically

関連テーマ