Update profile picture using Python ms-graph-sdk

Evans, Dean1 (GE Aerospace) 0 Reputation points
2024-04-05T16:59:48.03+00:00

I would like to add a mask to a users picture. I am able to get the picture and convert to jpeg, add the mask, convert back to binary and then try to load back to the user profile. The update method is failing and tried a few combinations:

AttributeError: 'bytes' object has no attribute 'serialize'

Thanks

response = await client.users.by_user_id('17c89e3d-f28f-459e-8738-cb4cfa17c3fe').photo.patch(body=img_bytes)
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,672 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. hossein jalilian 3,020 Reputation points
    2024-04-05T18:18:54.8766667+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    This should resolve the AttributeError you encountered.

    import base64 
    
    img_base64 = base64.b64encode(img_bytes).decode('utf-8')  
    
    response = await client.users.by_user_id('17c89e3d-f28f-459e-8738-cb4cfa17c3fe')
    .photo.patch(body={
        '@odata.type': 'microsoft.graph.profilePhoto',
        'id': 'User photo ID', 
        'content': img_base64, 
    })
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful