Over a million developers have joined DZone.

How do i automate creating these posts images

DZone's Guide to

How do i automate creating these posts images

Free Resource


#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'cairo' # gem install cairo

IMAGE_PATH = '/path/to/image/file.png'

# open image as Cairo surface
image = Cairo::ImageSurface.from_png(IMAGE_PATH)
# this is out target surface we will paint on it
# and save it at the end, we created it a perfect Square
target = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, image.width, image_width)
# context is what enable us to paint
# a wrapper of any surface and used to
# define what we'll paint and where (the source and mask)
cr = Cairo::Context.new(target)

# to crop `image` we'll
# put it as source, then
# draw a mask on the target
# then fill the space with this image
cr.set_source image
cr.rectangle 0, 0, image.width, image_width

# draw a white semi-transparent
# rectangle on it that we will
# write the post title on it.
cr.set_source_rgba 1, 1, 1, 0.8 # white with 80% alpha
cr.rectangle 0, image_width - 80, image.width, 80

# write title using Futura font in 30 pixels
cr.set_source_rgb 207.0/255, 35.0/255, 64.0/255
cr.select_font_face "Futura", 
cr.move_to 25, image_width - 40
cr.set_font_size 30
cr.show_text title

# write a small text under the title to tell
# user that we cropped the original image
cr.set_source_rgb 131.0/255, 17.0/255, 45.0/255
cr.select_font_face "Verdana", 
cr.move_to 25, image_width - 15
cr.set_font_size 14
cr.show_text "As this script is too long, check the rest of it from the link in description"

# then save the target surface to disk :)
cr.target.write_to_png IMAGE_PATH

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}