0

I have a base64 image and I want to cut the image into 2 or more parts at given heights. What is the most efficient way of doing it in python ?

One way to go is to convert base64 to convert base64->bytes->ndarray->bytes. But I'm facing a problem in ndarray->bytes conversion.

from scipy import ndimage
import base64,io
import numpy as np
import matplotlib.pyplot as plt

i1 = 'base64 of your sample png image'
b64=i1.replace('data:image/png;base64,','')
byts = io.BytesIO(base64.b64decode(b64)) # base64->bytes conversion
img_array = ndimage.imread(byts)   #bytes->ndarray conversion
part1=img_array[0:100]
part2=img_array[100:150]

# now i want to convert part1 and part2 to bytes, but how ?
part1_bytes = part1.tobytes()
# but when I save part1_bytes into a file and open it in my pc, it says an invalid image

After I split the images, I want to convert each part into buffer. I cant figure how. Even if I could do all these conversions it seems very indirect and lengthy. I want to know how to vertically split base64 image into multiple images or any better workaround you suggest.

Note : This answer addresses the same issue I have, but I cant get the logic.

Uchiha Madara
  • 984
  • 5
  • 16
  • 35
  • 1
    It doesn't seem like it would be possible to slice bytes out of the image data and get back valid image (see [here](http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html)). It should be fairly straightforward to do this directly with [`PIL`](http://pillow.readthedocs.io/en/4.3.x/handbook/tutorial.html#cutting-pasting-and-merging-images). –  Nov 15 '17 at 08:02
  • @Blurp, Thanks so much. A simple `PIL.crop` worked. I made it too complicated. – Uchiha Madara Nov 15 '17 at 08:36

0 Answers0