For creating or editing images for social media, I generally use any of the following tools:
I usually prefer SVG over other formats, and have some templates for Instagram, that I modify whenever I have to announce a new blog post.
There's a GitLab repository where I upload JSON files with the content of every new post, where there's a Python script that takes care of posting to DEV, then shares the link on a new Post on X. I needed another script for editing the following image:
Image Editing
In the SVG, there's a <tspan>
element with id='tspan1'
that contains the text to modify Text
. To edit it, you can use the xml.etree.ElementTree
Python module as follows:
import subprocess
import os
import tempfile
import xml.etree.ElementTree as ET
file_name = "new-post.svg"
new title = "SVG: Image Editing and Convertion with Python"
with open(file_name, 'r', encoding='utf-8') as file:
svg_content = file.read()
root = ET.fromstring(svg_content)
target_element = root.find(".//*[@id='tspan1']")
target_element.text = new_title
modified_svg = ET.tostring(root, encoding='unicode')
Previous code block does:
- Read the content of the SVG file
- Treat the content of the SVG file as XML with the
ElementTree
module - Find the
<tspan>
element - Replace the title
- Convert the modified XML back to string
Image Convertion
Now to convert the modified SVG to PNG:
output_file = "new_post.png"
width = 1080
height = 1080
with tempfile.NamedTemporaryFile(mode='w', suffix='.svg', delete=False, encoding='utf-8') as temp_svg:
temp_svg.write(modified_svg)
temp_svg_path = temp_svg.name
command = [
"inkscape",
temp_svg_path,
f"--export-filename={output_file}",
f"--export-width={width}",
f"--export-height={height}"
]
result = subprocess.run(command, check=True, capture_output=True, text=True)
os.remove(temp_svg_path)
Previous code does:
- Create a temporary SVG file with the content of the
modified_svg
variable - Run Inkscape from the command line to convert the file to PNG
- Remove the temporary file
Once you run previous script, you will get the following picture in the same directory:
Top comments (0)