Image manipulation with n8n and code-node (python)

I want to make some changes to an images with python (using PIL or something similar). Could somebody give me an example on how to do this? The biggest problem for me is to load the image.

Could somebody create an example code how to get an image from the previous node, convert it to black and white and output it?

Thanks in advance!

code for python:

from PIL import Image

image_path = 'path_to_your_image.jpg' #### How to do this in n8n by loading the image from the the previous node?
image = Image.open(image_path)

bw_image = image.convert('L')

bw_image.save('path_to_save_bw_image.jpg') #### How to return the image properly?

edit:
I successfully loaded the image, but getting this error:
ERROR: AttributeError: convert

from PIL import Image
image = _input.all()
bw_image = image.convert('L')
return bw_image

Anyone knows a suitable solution for this? Or is it generally impossible to do image manipulation with the code node?
(I know the ā€œEdit Imageā€ node, but the functionality is too limited for my case)

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

hello @schnipo

You need the binary data, not the json. Itā€™s accessible via _input.last().binary.data.data and itā€™s a base64 encoded.

1 Like

Hi @barn4k
thank you very much for your fast reply. I canā€™t figure out how to debug it, it always throws the error:
ERROR: TypeError: a bytes-like object is required, not ā€˜strā€™

Can you help me with this simplified workflow?

That one works

3 Likes

awesome, thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.