unwitting
unwitting

Reputation: 3396

Solutions for Image Manipulation in Core Python

I have a requirement to perform some simple image manipulation in Python, with the constraint that I can't assume the presence of anything but standard Python - no third party modules, not even PIL.

The actual function I need is scaling - preferably something more than simple pixel dropping or keeping, so some interpolation to produce an OK-looking image. As far as I can think, my options are:

  1. Use imageop - this is only available in Python 2 and does not perform interpolation on scaling.
  2. Directly include the code of some legally usable image manipulation library in my code, or at least the portions required for my task.

I have two questions, really:

  1. Is there another approach anyone can think of that I could take here?
  2. If I was to go for option 2. above, which library would you recommend and why? Which would make it the easiest to include only the required code etc?

Upvotes: 1

Views: 769

Answers (1)

aidanhs
aidanhs

Reputation: 102

You can package the pure python pymaging library with your application for only a 40K overhead.

$ git clone https://github.com/ojii/pymaging.git
Cloning into 'pymaging'...
[...]
$ (cd pymaging && zip -r pymaging.zip pymaging/)
  adding: pymaging/ (stored 0%)
[...]
$ (echo 'pymaging_zip = """' && base64 pymaging/pymaging.zip && echo '"""') > out.py
$ cat >> out.py <<'EOF'
import tempfile
import os
import sys
import base64
pymaging_tmp_fd, pymaging_tmp_path = tempfile.mkstemp(suffix='.zip')
os.write(pymaging_tmp_fd, base64.b64decode(pymaging_zip))
os.close(pymaging_tmp_fd)
sys.path.append(pymaging_tmp_path)
import pymaging
EOF
$ wc -c out.py
40420 out.py

This packs up the pymaging library into a zip file which is then embedded into your application. It writes the zip file to a temporary file and then uses Python's ability to import libraries from zip files.

You should probably consider cleaning up the temporary file afterwards, especially if this is to be used on Windows.

Upvotes: 2

Related Questions