I'm trying to use PIL to composite some aerial imagery and running into some trouble. I use PIL to load this image with this little bit of code:
composite = Image.new('RGBA', (256, 256))
url = 'http://...'
resp = requests.get(url)
content = StringIO(resp.content)
image = Image.open(content)
composite.paste(image, (0, 0), image)
When I make the call to composite.paste()
, PIL gives me the error "ValueError: bad transparency mask". When I print image.mode
, sure enough it's simply RGB
instead of the expected RGBA
(which paste()
requires).
Where does the alpha channel on my downloaded PNG go?
The below code is working for me. The key is to use image.convert('RGBA')
.
from PIL import Image
import requests
import StringIO
url = "https://gis.apfo.usda.gov/arcgis/rest/services/NAIP/Tennessee_2016_60cm/ImageServer/exportImage?bbox=-87.1875,34.3071438563,-84.375,36.5978891331&bboxSR=4326&size=256,256&imageSR=102113&transparent=true&format=png&f=image"
resp = requests.get(url)
content = StringIO.StringIO(resp.content)
image = Image.open(content)
image = image.convert('RGBA')
composite = Image.new("RGBA", image.size, (255,255,255,0))
composite.paste(image )