wtorek, 3 lutego 2015

GIMP - how to export image to base64

That was somewhat extremely surprising to me that GIMP does not provide Base64 exporter out of the box (but I am not the GIMP expert - maybe there is ;)). Nonetheless, as it seems to me a quite straightforward to implement such feature, I faced the challenge. After short googling and refreshing deep buried Python knowledge, it became simple, amazingly simple in fact. Here you are some details in three simple steps: 0. Open "Python Console" (don't be afraid, it does not bite you, or choke either ;)
Go to "Filters" menu -> "Python-Fu". The python console should appear.
1. Take an image
img = gimp.image_list()[0]  // assuming you'd got just one image opened
2. Read all bytes
bytes = open(img.filename, "rb").read()
3. Encode bytes with 'base64' algorithm

And for "one-liner" fanboys, we can compact it into one line:

open(gimp.image_list()[0].filename, "rb").read().encode('base64')
bytes.encode('base64') puts some new-line characters, alternatively you can use the following:
import base64
base64.b64encode(open(gimp.image_list()[0].filename, "rb").read())
Reference: Python Scripting Official Doc

4 komentarze:

  1. Thanks for this great post! Inspired by this (and in the need for such solution at my work) I've written today this plugin: https://github.com/sirmacik/gimp-plugin-base64_file_encoder

    Hope others will find it useful too.


  2. Thanks for inspiring sirmacik who insired me https://github.com/CrandellWS/base64-gimp-plugin/releases

    Dzięki za inspirującą sirmacik którzy mnie insired https://github.com/CrandellWS/base64-gimp-plugin/releases

  3. If you're on a linux command line you can simply say
    base64 -w 0 filename.png