Upload And Set Office 365 Profile Image Using Microsoft Graph API

In my previous article, I explained how to fetch access tokens to consume Graph API. In this article, we will discuss how to change Office 365 profile image from SharePoint using Microsoft Graph API.
 
My previous articles related to Microsoft Graph API from the below links.
Update User Profile Photo
 
Users are able to update the Office 365 from the following endpoints. You can use either PATCH or PUT operations for updating the profile picture.

Graph API endpoint: https://graph.microsoft.com
 
PUT https://graph.microsoft.com/me/photo/$value
PUT https://graph.microsoft.com/users/{user id | user Principalname}/photo/$value
PUT https://graph.microsoft.com/groups/{id of the office 365 group}/photo/$value
PUT https://graph.microsoft.com/contacts/{ id }/photo/$value
PUT https://graph.microsoft.com/users/{user id | userpricipalname}/contacts/{id}/photo/$value
PUT https://graph.microsoft.com/users/{user id | userpricipalname}/contactfolders/{contactFolderId/contacts/{id}/photo/$value 
 
PATCH https://graph.microsoft.com/me/photo/$value
PATCH https://graph.microsoft.com/users/{user id | user Principalname}/photo/$value
PATCH https://graph.microsoft.com/groups/{id of the office 365 group}/photo/$value
PATCH https://graph.microsoft.com/contacts/{ id }/photo/$value
PATCH https://graph.microsoft.com/users/{user id | userpricipalname}/contacts/{id}/photo/$value
PATCH https://graph.microsoft.com/users/{user id | userpricipalname}/contactfolders/{contactFolderId/contacts/{id}/photo/$value
 
Permissions
 
Retrieve user photo user.readwrite, user.readwriteall
Retrieve the group photo group.readwrite
Retrieve the contact photo contact.readwrite 
 
So now, I am going to create a function named "requestToken()" to fetch the access token passed into the AJAX request header to authorize the API request.
 
Code
  1. function requestToken() {  
  2.   
  3.        $.ajax({  
  4.            "async"true,  
  5.            "crossDomain"true,  
  6.            "url""https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie    
  7.            "method""POST",  
  8.            "headers": {  
  9.                "content-type""application/x-www-form-urlencoded"  
  10.            },  
  11.            "data": {  
  12.                "grant_type""client_credentials",  
  13.                "client_id ""8baf0301-27df-44b1-b4fe-7911b9a918de"//Provide your app id    
  14.                "client_secret""DxSF1K+JKl7LWJK8+3Ibg4il5JM4qUvdwOtShsYNvEA="//Provide your secret    
  15.                "scope ""https://graph.microsoft.com/.default"  
  16.            },  
  17.            success: function(response) {  
  18.                console.log(response);  
  19.                token = response.access_token;  
  20.                  
  21.            }  
  22.   
  23.        })  
  24.    }  
 In the console window, you are able to see the success response that looks like below.
 
 SharePoint
 
In the next step, we are going to create a function "uploadPhoto()" to upload a photo to Office 365.

HTML
  1. <div class="upload-btn-wrapper">  
  2.   <button class="btn" type="button" onclick=" UploadPhoto();">Upload a file</button>  
  3.   <input type="file" name="myfile" id="testFile" />  
  4. </div>  
REQUEST
  1. function uploadPhoto(){  
  2.     var file = document.getElementById('testFile').files[0];  //FETCH THE FILE FROM FILE UPLOAD CONTROL
  3.    
  4.             $.ajax({  
  5.             method: 'PATCH',   
  6.             url: "https://graph.microsoft.com/v1.0/users/[email protected]/photo/$value",  
  7.             data:  file,                       //pass DATA from the variable file
  8.             processData: false,   
  9.             headers: {  
  10.                 'Authorization''Bearer ' + token,          // THE ACCESS TOKEN HERE ALREADY RECEIVED WHEN REQUEST TOKEN FUNCION CALLS
  11.                  'Content-Type''image/jpeg'                // SET THE CONTENT TYPES AS IMAGE/JPEG
  12.             },  
  13.         }).success(function (response) {  
  14.             alert("Photo uploaded successfully");  
  15.         //  retriveuserPhoto();  
  16.               
  17.         }).error(function (error) {});  
  18.   
  19.       }  
 Now, add a Content Editor Web Part and render the HTML.
 
SharePoint
 
SharePoint
 
After successfully picking the image file, click "Upload a file" button.
 
SharePoint 
 
Now, I am going to create a function "retriveuserPhoto()" to retrieve the uploaded photo from Office 365.
 
GET https://graph.microsoft.com/users/{userid | userprincipalname} /size/photo/$value
 
A successful request returns the binary data of the image.
 
 HTML
  1. <img id="office365" src=''>  
Code
  1. function retriveuserPhoto(){  
  2.     
  3.             $.ajax({  
  4.             method: 'GET',  
  5.              
  6.             url: "https://graph.microsoft.com/v1.0/users/[email protected]/48x48/photo/$value",  //url with size of the photo
  7.               
  8.             headers: {  
  9.                 'Authorization''Bearer ' + token,   // pass the access token here
  10.                     
  11.             },   
  12.         }).success(function (image) {  
  13.             console.log(image);  
  14.              var blob = new Blob(  
  15.               
  16.               [image],  
  17.               
  18.               {type : 'image/jpeg'}  Convert the response into blob with content type image/jpeg                      
  19. );   
  20. var url = window.URL || window.webkitURL;  
  21. var blobUrl = url.createObjectURL(blob);  // Use the javascript object to construct a blob image url
  22. $('#office365').attr("src", blobUrl);  //bind the BLOB url into image tag
  23.   
  24.         }).error(function (error) {});  
  25.   
  26.       }  
Output
 
SharePoint 
 
SharePoint

Now, you are able to update and get photos from Office 365 using Microsoft Graph API.
 
Happy SharePointing!