---
title: User avatars
related:
  - https://docs.kentico.com/13/managing-users.md
  - https://docs.kentico.com/13/configuring-xperience/managing-sites/configuring-settings-for-sites/settings-security-membership/settings-avatars.md
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

Avatars are images associated with user accounts. They can be displayed, for example, on a user's public profile. Avatars serves as graphical representations of users and are often used to personalize user contributions on websites.

## Managing user avatars

Site users can manage avatars either in the administration interface or on the live site, depending on their [privilege level](https://docs.kentico.com/13/managing-users/user-management.md):

- **Site administrators** can change the avatar of any user:
  1. Open the **Users** application.
  2. **Edit** () a user and switch to the **Settings** tab.
  3. Change the user's avatar in the **User picture** field.

     ![Changing a user's avatar](https://docs.kentico.com/docsassets/13/user-avatars/Changing_Avatars_Users_Application.png "Changing a user's avatar")
- **Users with access to the administration interface** can set their avatar in the **My profile** application on the **Details** tab.
- **Regular site users** can upload or change their avatars after site developers [implement](#working-with-user-avatars-on-the-live-site) avatar support on the live site. The steps required to change user avatars then depend entirely on the custom implementation. Typically on most websites, avatar management can be found in an "account management" section.

> **Info:** By default, newly created or registered users do not have an avatar associated with them in the system.

## Limiting the size of avatar images

Site administrators can [configure](https://docs.kentico.com/13/configuring-xperience/managing-sites/configuring-settings-for-sites/settings-security-membership/settings-avatars.md) the maximum size for user-uploaded avatar images in the **Settings** application under **Security & Membership** -> **Avatars**. The system resizes all uploaded avatar images to fit these constraints.

## Working with user avatars on the live site

Before regular site users can use the avatar functionality, site developers need to implement support for displaying and manipulating user avatars.

The system provides the following API developers can leverage when implementing user avatar support on the live site (as part of the _Kentico.Content.Web.Mvc_ namespace):

- **IAvatarService** – service used to retrieve and update user avatars. It provides the following methods:
  - **bool UpdateAvatar** – sets or updates an existing avatar for the specified user. The avatar is bound to the user and cannot be selected by other users. When the users changes their avatar, their previous avatar is deleted from the system.

    > **Info:** When processing uploaded files, the _UpdateAvatar_ method checks whether the extension of the uploaded file is included in the list of allowed extensions in _Settings -> System -> Files ->_ _Upload extensions_ and resizes the image to fit the dimensions configured in the [avatar settings](#limiting-the-size-of-avatar-images).
  - **string GetAvatarUrl** – returns an application relative virtual URL (starting with \~/) for the avatar of the specified user.
  - **void DeleteAvatar** – deletes the avatar image associated with the specified user.
- **Url.Kentico().AvatarUrl(string userName)** – extension method for _System.Web.Mvc.UrlHelper_ that returns the absolute URL of the avatar for the specified user. The method has the following optional parameters:
  - **string pathToDefaultAvatar** – relative path to a default avatar image displayed for users with no assigned avatar. For example, "_\~/Content/Images/default-avatar.png_".
  - **int maxSideSize** – constrains the avatar image so that its larger side's dimension matches the entered value. Aspect ratio is preserved and the width and height settings are not applied. Note that the maximum avatar size is given by the [avatar settings](#limiting-the-size-of-avatar-images) (i.e., the method does not upscale the image). The default avatar image is unaffected by this parameter.
  - **int width, height** – constrains the maximum width or height of the avatar image, respectively. Note that the maximum avatar size is always given by the [avatar settings](#limiting-the-size-of-avatar-images) (i.e., the method does not upscale the image). The default avatar image is unaffected by these parameters.

The following set of examples demonstrates the usage of the avatar API on the live site.

### Displaying user avatars

To display user avatars, call the _Url.Kentico().AvatarUrl_ extension method in the code of your views. For example:

```csharp

@using Kentico.Membership.Web.Mvc

@model Kentico.Membership.User

...

<img src="@Url.Kentico().AvatarUrl(Model.UserName, pathToDefaultAvatar: "~/Content/Images/default-avatar.png")" />

...

```

This snippet renders an _img_ tag with the given user's avatar. If the user has no avatar image assigned, it displays the image specified in the _pathToDefaultAvatar_ parameter.

### Implementing an avatar uploader

This section demonstrates the implementation of a simple avatar uploader. The uploader allows site users to change the avatar image associated with their account:

> **Tip:** **Tip**: To view the full code of a functional example, you can inspect and download the [LearningKit project](https://github.com/Kentico/LearningKit-Mvc) on GitHub. You can also run the LearningKit website by connecting the project to a Xperience database. Follow the instructions in the repository's README file.

1. Initialize an instance of _IAvatarService_ in the controller class used to manage user account activities on your website.

   ```csharp

           private readonly IAvatarService avatarService;
           private readonly IEventLogService eventLogService;

           public AccountController(IAvatarService avatarService,
                                    IEventLogService eventLogService)
           {
               // Initializes an instance of a service used to manage user avatars
               this.avatarService = avatarService;
               this.eventLogService = eventLogService;
           }


   ```
2. Add a new action that handles uploaded avatars and assigns them to users.

   ```csharp

           [HttpPost]
           [ValidateAntiForgeryToken]
           [Authorize]
           public ActionResult ChangeAvatar(HttpPostedFileBase avatarUpload)
           {
               object routevalues = null;

               // Checks that the avatar file was uploaded
               if (avatarUpload != null && avatarUpload.ContentLength > 0)
               {   
                   // Gets the representation of the user requesting avatar change from Xperience
                   var user = KenticoUserManager.FindByName(User.Identity.Name);
                   // Attempts to update the user's avatar
                   if (!avatarService.UpdateAvatar(avatarUpload.ToUploadedFile(), user.Id, SiteContext.CurrentSiteName))
                   {
                       // If the avatar update failed (e.g., the user uploaded an image with an usupported file extension)
                       // sets a flag for an error message in the corresponding view
                       routevalues = new { avatarUpdateFailed = true };
                   }
               }

               return RedirectToAction("EditUser", "Account", routevalues);
           }


   ```

   The _avatarUpdateFailed_ flag controls the display of an error message to the user in the corresponding view. It should be set to false by default in the controller action handling the uploader display (e.g., on the user account overview page):

   ```csharp

   public ActionResult EditUser(bool avatarUpdateFailed = false)
   {
       // Finds the user based on their current user name
       User user = KenticoUserManager.FindByName(User.Identity.Name);

       EditUserAccountViewModel model = new EditUserAccountViewModel() 
       {
           User = user,
           AvatarUpdateFailed = avatarUpdateFailed
        };

        return View(model);
   }

   ```
3. Update the corresponding view to render user avatars and add avatar update functionality. In this example, the form handling the avatar image submit is hidden and invoked when the user clicks on the _Change avatar_ button. The [submit()](https://www.w3schools.com/jsref/met_form_submit.asp) method call bound to the _onchange_ event of the text box form input ensures the form is immediately submitted after a user selects an avatar using the browser's file explorer.

   ```csharp

   @using Kentico.Membership.Web.Mvc

   <div>
       <h2>User Avatar</h2>
       <div>
           @* Generates a link to a user's avatar (or a default one if specified and a user avatar is not found).
               Note that the properties constraining avatar dimensions do not work for default avatars. *@
           <img src="@Url.Kentico().AvatarUrl(Model.User.UserName, maxSideSize: 500, width: 500, height: 500, pathToDefaultAvatar: " ~/Content/Images/default-avatar.png")" />

           <br />

           <button>
               <div onclick="document.getElementById('avatarUpload').click()">Change avatar</div>
           </button>
       </div>

       @* Displays an error message in case the user uploaded a file with an unsupported file extension.
           Supported file extensions can be configured in Settings -> System -> Files -> Upload extensions in the Administration interface. *@
       @if (Model.AvatarUpdateFailed)
       {
           <div>
               <span>Please upload a valid image file.</span>
           </div>
       }

       @using (@Html.BeginForm("ChangeAvatar", "Account", FormMethod.Post, new { enctype = "multipart/form-data", id = "avatarUploadForm", style = "display:none;" }))
       {
           // Generates a hidden field holding an anti-forgery token
           // The Xperience API version of this method ensures tokens are correctly generated for pages where output caching is enabled
           @Html.Kentico().AntiForgeryToken()
           @Html.TextBox("avatarUpload", "", new { type = "file", id = "avatarUpload", accept = "image/*", onchange = "document.getElementById('avatarUploadForm').submit()" })
       }
   </div>


   ```

The site's users can now change their avatars at will using the avatar uploader.

### Deleting user avatars

To allow users to delete their avatars, create a controller action that calls the _IAvatarService.DeleteAvatar_ method:

```csharp

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult DeleteAvatar(int userId)
        {
            // Deletes the avatar image associated with the user
            avatarService.DeleteAvatar(userId);

            return RedirectToAction("EditUser", "Account");
        }


```

The method removes the avatar image from the user and deletes the associated avatar object from the system. You can then extend the view of the page where users manage their account, and add a HTML form that posts the user ID of the current user to the given action.
