Get image from multipart response from a Web Coverage Service (WCS) using python

49 Views Asked by At

I'm trying to get elevation data from a WCS service using python and owslib. I managed to get a response but I haven't managed to extract the useful information.

This code provides an example of the response

from owslib.wcs import WebCoverageService

wcs_url = "https://geo.api.vlaanderen.be/DHMV/wcs?"

bbox_vla = (102200, 192500, 102700, 193000)

# Connect to WCS service
wcs = WebCoverageService(wcs_url)

response = wcs.getCoverage(identifier=['DHMVII_DTM_1m'],
    bbox=bbox_vla,
    format='image/tiff',
    crs='EPSG:31370',
    subsets= [('x', 102200, 102700), ('y', 192500, 193000)],
    scalefactor=2
)

The response information says the content-type is 'multipart/related'.

{'Date': 'Thu, 18 Jan 2024 08:35:44 GMT', 'Content-Type': 'multipart/related; boundary="wcs";start="GML-Part";type="text/xml"', 'Content-Length': '131127', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Server': 'Microsoft-IIS/10.0', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block', 'X-Powered-By': 'ARR/3.0, ASP.NET', 'Access-Control-Allow-Origin': '*'}

I have been trying to get the .tif file using the email library but I have'nt been able to do it. Does anyone know a library or a way to get the .tif file? There's a similar question in the forum, but it has no answers.

Thanks in advance.

1

There are 1 best solutions below

0
stray_dog On

In the case someone encounters the same issue I ended up solving the problem like this:

# This boundary appears in the header
boundary = b"--wcs"

# Split into different parts
bytes_parts = response_s2.read().split(boundary)

for part in bytes_parts:
    if part.startswith(b"\nContent-Type: image/tiff"):
        # The tif should start with "II*"
        index = part.index(b"II*")
        image_tif = part[index:]

with open("test.tif", "wb") as f:
    f.write(image_tif)

I tried with the email module and other libraries but couldn't do it for whatever reason.