0

I'm trying to make a little weather forecast program which gives you an image with an overview of the weather in python

To get the weather, I'm using openweathermap and it works ok for me, but for the image I'm using PIL to paste the weather icon, but for some reason there's a part of it that's not being pasted, here you can see what the icon should be: https://openweathermap.org/img/wn/04n@2x.png, and here's how it appeared in the image that came out of my script: enter image description here

Here's the part of the code that generates the image:

def drawImage(d):
    img=PIL.Image.open("base.png")

    url=f"https://openweathermap.org/img/wn/{d['icon']}@2x.png"
    weatherIcon=Image.open(requests.get(url, stream=True).raw)
    print(url)
    img.paste(weatherIcon, (00, 10))

    now=datetime.now()
    name="boards/"+now.strftime('%d_%m_%Y_%H_%M_%S')+".png"
    img.save(name)
    return name

Some notes on this code:

  • The base.png is just a 720x720 blank image
  • The d that gets passed in is a dictionary with all the information, but here it only needs the icon, so I'll give this example: {"icon": "04n"}
  • I got the URL for the image from the website of OpenWeatherMap, see documentation: https://openweathermap.org/weather-conditions
JasperDG
  • 137
  • 1
  • 3
  • 7

1 Answers1

1

This is happening because the icon image you download has transparency (an alpha channel). To remove that, you can use this answer.

I've simplified it slightly, define the following function:

def remove_transparency(im, bg_colour=(255, 255, 255)):
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
        alpha = im.getchannel('A')
        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg
    else:
        return im

and call it in your code:

weatherIcon=Image.open(requests.get(url, stream=True).raw)
print(url)
weatherIcon = remove_transparency(weatherIcon)
img.paste(weatherIcon, (00, 10))

You might want to adjust that bg_colour parameter.

joao
  • 2,220
  • 2
  • 11
  • 15
  • Great! Since posting this, I thought it could probably be simplified even more: once we have the alpha, maybe use mask=alpha directly on the final paste and avoid an intermediate paste on the bg image. – joao May 16 '21 at 08:32