in_memory png to base64 string

1893
7
02-24-2017 10:39 AM
JasonLevine
Occasional Contributor II

Does anyone know how to convert an in memory png to a base64 string?

My raster is defined as:

png = "in_memory\my_png.png"

I then try to convert it:

import base64

base64_string = str(base64.b64encode(png))

base64_string gets populated as: aW5fbWVtb3J5XG15X3BuZy5wbmc=

Which, when decoded is: in_memory\my_png.png

...not exactly what I had in mind.  Is this even possible do do in a geoprocessing script?

Thanks,

Jason

Tags (2)
0 Kudos
7 Replies
TomSellsted
MVP Regular Contributor

Jason,

I had done something similar, but was loading an image file from disk.  To encode it I had to read it.  Something like:

with open(driverPhoto, "rb") as imageFile:
    encodedPhoto = base64.b64encode(imageFile.read())

Perhaps you have to do a read as well.

Regards,

Tom

0 Kudos
JasonLevine
Occasional Contributor II

Tom,

Good idea...however, python doesn't seem to want to open an "in_memory" raster:

Runtime error
Traceback (most recent call last):
  File "<string>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'in_memory\\my_png.png'

Thanks,

Jason

0 Kudos
TomSellsted
MVP Regular Contributor

Jason,

It should already be open, I was suggesting that you read it.  Could you provide the code you have attempted?

Regards,

Tom

0 Kudos
JasonLevine
Occasional Contributor II

I'm using arcpy.CopyRaster_management to copy a local tiff into an in memory png:

tiff = r'C:\Temp\my_tif.tif'

png = r'in_memory\my_png.png'

CopyRaster_management(tiff, png, pixel_type='32_BIT_SIGNED', format='PNG')

f = open(png)

0 Kudos
TomSellsted
MVP Regular Contributor

Jason,

Thanks for the code, that gives me some context.  Maybe try:

tiff = r'C:\Temp\my_tif.tif'

png = r'in_memory\my_png.png'

CopyRaster_management(tiff, png, pixel_type='32_BIT_SIGNED', format='PNG')

 

b64 = base64.b64encode(png.read())

Regards,

Tom

0 Kudos
DarrenWiens2
MVP Honored Contributor

I'm surprised that it's possible to save a file in the in_memory workspace ending in '.png', although I see that you can. The file isn't actually .png format, though, it's a geodatabase raster (check the layer properties).

JasonLevine
Occasional Contributor II

You're right Darren, I was getting thrown off by the png extension.  It's not actually a png, it's a geodatabase raster.  It looks like you can only store "raster" in the in memory workspace.

0 Kudos