# Photo uploader

**Photo uploader** allows users to upload and manage an image used as avatar.

## Usage

The photo uploader allows users to upload an image via file browser. It optionally provides an edit dialog for cropping the image.

![Photo upload](<../images/photo-upload.png>)

### When to use

- In the user profile so the user can choose/change his avatar.
- When a user is created.

### Best practices

- The original image is kept (if necessary, a compressed version of it) so the user can undo the cropping.
- Display the compressed version of the image in the preview if compression is required.
- Adjust the size according to layout needs.
- The placeholder can use any of the [avatar](<https://element.siemens.io/components/status-notifications/avatar/>) colors.

## Design

### Elements

The photo uploader has different states based on the upload status:

- Initial state: When no image is uploaded, a placeholder with the user's initials will be shown.
- Image uploaded: Once a image is uploaded, options to remove or change the image will be displayed.

![Photo upload elements](<../images/photo-upload-elements.png>)

> 1. Initials, 2. Upload button, 3. Image, 4. Change button, 5. Remove button

Additionally, a dialog can be enabled to allow users to crop the image if necessary.

![Photo upload dialog elements](<../images/photo-upload-dialog-elemets.png>)

> 1. Title, 2. Description, 3.Image, 4.Crop mask, 5. Change image button, 6.Cancel and Apply button

### Mask shape

The image mask can be set to a square or rounded shape according to the layout.

![Photo upload shapes](<../images/photo-upload-shape.png>)

### Validation and image processing

To keep photo uploads simple, applications should automatically check image dimensions, file size, and format. Resize and compress images as needed, and convert them to a supported format such as JPEG or PNG when necessary. Preserve visual quality during these adjustments.

## Code

### Usage

The component `SiPhotoUploadComponent` makes use of the open source software [ngx-image-cropper](<https://github.com/Mawi137/ngx-image-cropper>). You need to add the [npm package](<https://www.npmjs.com/package/ngx-image-cropper>) to your project, before you can make use of the photo upload component.

Import the `SiPhotoUploadComponent` in your standalone component that shall provide a photo upload.

> [!NOTE]
>
> **Required Packages**
>
> - [ngx-image-cropper](<https://www.npmjs.com/package/ngx-image-cropper>) The currently supported dependency versions can be found in the [package.json of the demo app](<https://github.com/siemens/element/blob/main/package.json>).

```
import { Component } from '@angular/core';
import { SiPhotoUploadComponent } from '@siemens/element-ng/photo-upload';

@Component({
  selector: 'app-sample',
  template: `<si-photo-upload />`,
  imports: [SiPhotoUploadComponent]
})
export class SampleComponent {}
```

#### Adjust size

Consuming applications can customize the component size via the following CSS variables:

- `--si-photo-upload-photo-width` (default: `200px`)
- `--si-photo-upload-photo-height` (default: `200px`)

The snippet below shows how to use the Angular component styles attribute to adjust the size to `300px` x `300px`:

```
import { Component } from '@angular/core';
import { SiPhotoUploadComponent } from '@siemens/element-ng/photo-upload';

@Component({
  selector: 'app-sample',
  template: `<si-photo-upload />`,
  imports: [SiPhotoUploadComponent],
  styles:
    'si-photo-upload { --si-photo-upload-photo-width: 300px; --si-photo-upload-photo-height: 300px; }'
})
export class SampleComponent {}
```

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ContentActionBarMainItem } from '@siemens/element-ng/content-action-bar';
import { SiDashboardCardComponent } from '@siemens/element-ng/dashboard';
import { SiPhotoUploadComponent } from '@siemens/element-ng/photo-upload';
import { LOG_EVENT } from '@siemens/live-preview';

@Component({
  selector: 'app-sample',
  imports: [SiDashboardCardComponent, SiPhotoUploadComponent, FormsModule],
  templateUrl: './si-photo-upload.html'
})
export class SampleComponent {
  logEvent = inject(LOG_EVENT);
  readonly basePhoto = signal<string>('');
  readonly baseCroppedPhoto = signal<string>('');
  readonly sourcePhoto = signal<string>('');
  readonly sourcePhotoUrl = signal<string>('');
  readonly croppedPhoto = signal<string>('');
  roundedMask = true;
  disabledCropping = false;
  readonly = true;
  readOnlyActions: ContentActionBarMainItem[] = [
    { type: 'action', label: 'Edit', action: () => this.edit() }
  ];
  editActions: ContentActionBarMainItem[] = [
    { type: 'action', label: 'Save', action: () => this.save() },
    { type: 'action', label: 'Cancel', action: () => this.cancel() }
  ];
  actions = this.readOnlyActions;

  protected edit(): void {
    this.readonly = false;
    this.actions = this.editActions;
  }

  protected save(): void {
    this.readonly = true;
    this.actions = this.readOnlyActions;
    this.basePhoto.set(this.sourcePhoto());
    this.baseCroppedPhoto.set(this.croppedPhoto());
  }

  protected cancel(): void {
    this.readonly = true;
    this.actions = this.readOnlyActions;
    this.sourcePhoto.set(this.basePhoto());
    this.croppedPhoto.set(this.baseCroppedPhoto());
  }

  protected sourcePhotoChanged(photo?: string): void {
    this.logEvent('sourcePhotoChanged', photo ? photo.slice(0, 50) + '...' : photo);
    if (photo !== this.sourcePhoto()) {
      this.sourcePhoto.set(photo ?? '');
    }
  }

  protected sourcePhotoUrlChanged(url?: string): void {
    this.logEvent('sourcePhotoUrlChanged', url);
    if (url !== this.sourcePhotoUrl()) {
      this.sourcePhotoUrl.set(url ?? '');
    }
  }

  protected croppedPhotoChanged(croppedPhoto?: string): void {
    this.logEvent(
      'croppedPhotoChanged',
      croppedPhoto ? croppedPhoto.slice(0, 50) + '...' : croppedPhoto
    );
    if (croppedPhoto !== this.croppedPhoto()) {
      this.croppedPhoto.set(croppedPhoto ?? '');
    }
  }
}
```

Template:

```html
<div class="p-6">
  <si-dashboard-card heading="Max Xantos" actionBarViewType="expanded" [primaryActions]="actions">
    <div class="card-body card-text" body>
      <div class="d-inline-block text-center">
        <si-photo-upload
          #photoUpload
          autoColor="true"
          modalDescription="Select the part of the picture you want to use"
          placeholderAltText="MX"
          photoAltText="Photo alt text"
          acceptedUploadFormats=".png, .jpg, .jpeg"
          uploadErrorWrongType="Wrong file type. Supported file types: PNG, JPG, and JPEG"
          [sourcePhoto]="sourcePhoto()"
          [sourcePhotoUrl]="sourcePhotoUrl()"
          [croppedPhoto]="croppedPhoto()"
          [readonly]="readonly"
          [disabledCropping]="disabledCropping"
          [roundImage]="roundedMask"
          [maxFileSize]="2048"
          [cropperMinWidth]="50"
          [cropperMaxWidth]="0"
          [cropperMinHeight]="50"
          [cropperMaxHeight]="0"
          (sourcePhotoChange)="sourcePhotoChanged($event)"
          (croppedPhotoChange)="croppedPhotoChanged($event)"
        />
        <span>Max Xantos</span>
      </div>
    </div>
  </si-dashboard-card>

  <div class="card mt-6 e2e-ignore">
    <div class="card-header">Control panel</div>
    <div class="card-body">
      <div class="mb-6">
        <div class="form-check form-check-inline">
          <label>
            <input type="checkbox" class="form-check-input" [(ngModel)]="roundedMask" />
            <span class="form-check-label">Rounded Mask</span>
          </label>
        </div>
        <div class="form-check form-check-inline">
          <label>
            <input type="checkbox" class="form-check-input" [(ngModel)]="disabledCropping" />
            <span class="form-check-label">Disable Cropping</span>
          </label>
        </div>
      </div>
      <div class="row">
        <div class="col-6">
          <label for="sourcePhotoUrl" class="form-label"
            >Source photo URL (e.g. ./assets/images/beach.jpg)</label
          >
          <input
            type="text"
            class="form-control"
            id="sourcePhotoUrl"
            [ngModel]="sourcePhotoUrl()"
            (ngModelChange)="sourcePhotoUrlChanged($event)"
          />
          <label for="sourcePhoto" class="form-label">Source photo (base64 Data URL)</label>
          <textarea
            type="text"
            class="form-control"
            id="sourcePhoto"
            [ngModel]="sourcePhoto()"
            (ngModelChange)="sourcePhotoChanged($event)"
          ></textarea>
          <img
            class="mt-4"
            alt="Image within the photo-upload component"
            style="width: 300px"
            [src]="sourcePhoto()"
          />
        </div>
        <div class="col-6">
          <label for="croppedPhoto" class="form-label">Cropped photo</label>
          <textarea
            disabled
            type="text"
            class="form-control"
            id="croppedPhoto"
            [ngModel]="croppedPhoto()"
          ></textarea>
          <img class="mt-4" alt="Cropped image" style="width: 300px" [src]="croppedPhoto()" />
        </div>
      </div>
    </div>
  </div>
</div>
```

### Image cropping

To implement custom image cropping — whether in an upload dialog, an image editor, or a photo workflow — you can use the image cropper as a standalone component.

Simply wrap the `<image-cropper>` element from the [ngx-image-cropper](<https://github.com/Mawi137/ngx-image-cropper>) library with `<si-image-cropper-style>`.

This ensures the component matches Element’s theming while granting you full control over its configuration and behavior.

```
import { Component } from '@angular/core';
import { SiImageCropperStyleComponent } from '@siemens/element-ng/photo-upload';
import { ImageCropperComponent, ImageCroppedEvent } from 'ngx-image-cropper';

@Component({
  selector: 'app-sample',
  template: `
    <si-image-cropper-style>
      <image-cropper
        format="jpeg"
        [imageURL]="imageSource"
        [maintainAspectRatio]="true"
        [aspectRatio]="1"
        (imageCropped)="onImageCropped($event)"
      />
    </si-image-cropper-style>
  `,
  imports: [ImageCropperComponent, SiImageCropperStyleComponent]
})
export class SampleComponent {
  imageSource = 'path/to/your/image.jpg'; // URL to your image

  onImageCropped(event: ImageCroppedEvent) {
    // Handle the cropped image
    const croppedImage = event.base64;
    // Use the cropped image as needed
  }
}
```

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject } from '@angular/core';
import { SiImageCropperStyleComponent } from '@siemens/element-ng/photo-upload';
import { LOG_EVENT } from '@siemens/live-preview';
import { ImageCropperComponent, ImageCroppedEvent } from 'ngx-image-cropper';

@Component({
  selector: 'app-sample',
  imports: [ImageCropperComponent, SiImageCropperStyleComponent],
  templateUrl: './image-cropping.html',
  host: { 'class': 'p-5' }
})
export class SampleComponent {
  protected readonly logEvent = inject(LOG_EVENT);
  protected imageSource = 'assets/images/beach.jpg';

  protected onImageCropped(event: ImageCroppedEvent): void {
    this.logEvent('Image cropped', event);
  }
}
```

Template:

```html
<div class="card">
  <div class="card-header">
    <h5>Image cropper</h5>
  </div>
  <div class="card-body">
    <si-image-cropper-style>
      <image-cropper
        format="jpeg"
        [imageURL]="imageSource"
        [maintainAspectRatio]="true"
        [aspectRatio]="1"
        (imageCropped)="onImageCropped($event)"
      />
    </si-image-cropper-style>
  </div>
</div>
```

### Security considerations

The `sourcePhotoUrl` is marked as a trusted resource URL and is not sanitized by Angular. Only pass URLs from trusted sources.

### [SiPhotoUploadComponent](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L63-L556>)

**Kind:** component

**Selector:** `si-photo-upload`

```
import { SiPhotoUploadComponent } from '@siemens/element-ng/photo-upload';
```

A component used to upload, edit, and delete a user's photo. The user can upload a photo either via file browser or a URL to the photo. You can set the source photo with the `sourcePhoto` Data URL input or the `sourcePhotoUrl` URL input. If you already have a cropped image you can set it with the `croppedPhoto` input. Cropping changes are emitted via the `croppedPhotoChange` output.

```
component SiPhotoUploadComponent implements OnChanges, OnDestroy
```

#### Input Properties

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| [acceptedUploadFormats](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L89-L89>) | `string` | `'.png, .jpg, .jpeg'` | Accepted image formats for the file selection dialog.<br><br>See: [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file\#attr-accept](<https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-accept>) |
| [applyEditText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L207-L207>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.APPLY_PHOTO:Apply` `` | Text for the button applying the edited photo. |
| [autoColor](<https://github.com/siemens/element/blob/main/projects/element-ng/avatar/si-avatar-background-color.directive.ts#L44-L44>) | `boolean` | `false` | Automatically calculates the background color. If set, [color](<index.html#SiPhotoUploadComponent.color>) will be ignored. |
| [cancelEditText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L197-L197>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.CANCEL:Cancel` `` | Text for the button cancelling the editing process. |
| [changePhotoText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L153-L153>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.CHANGE_PHOTO:Change` `` | Text for the button changing the photo. |
| [color](<https://github.com/siemens/element/blob/main/projects/element-ng/avatar/si-avatar-background-color.directive.ts#L36-L36>) | `number` | `undefined` | The desired color index from $si-sys-color-data-categorical-\* color tokens. This can be set to any kind of positive integer that is then mapped to a color index. A better way to set a pseudo-random color is to set [autoColor](<index.html#SiPhotoUploadComponent.autoColor>) to `true`. |
| [croppedPhoto](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L311-L311>) | `string \| undefined` |  | The photo to be displayed and edited (when not readonly). |
| [cropperAspectRatio](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L236-L236>) | `number` | `1` | The width / height ratio (e.g. 1 / 1 for a square, 4 / 3, 16 / 9 ...). |
| [cropperContainWithinAspectRatio](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L253-L253>) | `boolean` | `false` | When set to true, padding will be added around the image to make it fit to the aspect ratio. Be aware that this transformation will cause the loaded image to be a png file with an increased base64 string payload. |
| [cropperFrameAriaLabel](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L163-L165>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.CROPPER_FRAME_LABEL:Crop picture` `` | Cropper frame aria label. |
| [cropperImageFormat](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L229-L229>) | `"png" \| "jpeg"` | `'jpeg'` | Output format of the edited image. |
| [cropperMaintainAspectRatio](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L244-L244>) | `boolean` | `true` | Whether to keep the width and height of the cropped image equal according to the aspectRatio. |
| [cropperMaxHeight](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L286-L286>) | `number` | `0` | The cropper´s height cannot be made bigger than this number of pixels. Default is 0 (disabled). |
| [cropperMaxWidth](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L278-L278>) | `number` | `0` | The cropper´s width cannot be made bigger than this number of pixels. Default is 0 (disabled). |
| [cropperMinHeight](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L270-L270>) | `number` | `50` | The cropper´s height cannot be made smaller than this number of pixels (relative to original image´s size). Will be ignored if `cropperMaintainAspectRatio` is set. (0 = disabled). |
| [cropperMinWidth](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L261-L261>) | `number` | `50` | The cropper´s width cannot be made smaller than this number of pixels (relative to original image´s size). (0 = disabled). |
| [disabledCropping](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L78-L78>) | `boolean` | `false` | Optionally disable image cropping. |
| [maxFileSize](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L96-L96>) | `number` | `2048` | Maximum allowed file size of the uploaded file in kilobytes. |
| [modalDescription](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L222-L222>) | `TranslatableString \| undefined` |  | Text displayed as description of the editing modal. |
| [modalHeader](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L217-L217>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.MODAL_TITLE:Profile picture` `` | Text displayed as header of the editing modal. |
| [photoAltText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L135-L135>) | `TranslatableString` | `''` | Alternative text for the photo. |
| [placeholderAltText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L143-L143>) | `TranslatableString` | `''` | Alternative text for the photo´s placeholder. The value will be used to calculate the background color when `autoColor` is true. |
| [readonly](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L71-L71>) | `boolean` | `false` | Indicate that changing or uploads are disabled. |
| [removePhotoText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L187-L187>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.REMOVE:Remove` `` | Text for the button removing the photo. |
| [roundImage](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L295-L295>) | `boolean` | `true` | Set this to true for a round cropper. Resulting image will still be square, but visually clipped with a border-radius: 50% on the resulting image to show it as round. |
| [sourcePhoto](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L301-L301>) | `string \| undefined` |  | The input photo to be used for cropping. A string in [Data URL](<https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs>) format with base64 encoding. |
| [sourcePhotoUrl](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L306-L306>) | `string \| undefined` |  | URL to a photo to be used for cropping. |
| [uploadErrorTooBig](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L123-L128>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.ERROR_FILE_SIZE_EXCEEDED:Current file size of {{mb}} MB exceeds file size of max. {{maxSizeMb}} MB` `` | If the uploaded file exceeds the allowed upload size, this error message will be displayed to the user. |
| [uploadErrorWrongType](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L107-L112>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.ERROR_FILE_TYPE:The image file is not valid. Please upload a PNG or JP(E)G.` `` | If the uploaded file is of an unsupported type, this error message will be displayed to the user. |
| [uploadPhotoText](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L175-L177>) | `TranslatableString` | `` $localize`:@@SI_PHOTO_UPLOAD.UPLOAD_PHOTO:Upload picture` `` | Text for the button uploading a photo. |

#### Output Properties

| Name | Type | Description |
| --- | --- | --- |
| [croppedPhotoChange](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L311-L311>) | `string \| undefined` | The photo to be displayed and edited (when not readonly). |
| [sourcePhotoChange](<https://github.com/siemens/element/blob/main/projects/element-ng/photo-upload/si-photo-upload.component.ts#L301-L301>) | `string \| undefined` | The input photo to be used for cropping. A string in [Data URL](<https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs>) format with base64 encoding. |

### Types Documentation

### [TranslatableString](<https://github.com/siemens/element/blob/main/projects/element-translate-ng/translate-types/global.types.ts#L18-L18>)

**Kind:** type alias

```
import type { TranslatableString } from '@siemens/element-translate-ng/translate-types';
```

Represents a translatable string. This can either be a translation key, e.g. `ACTIONS.EDIT` that will be automatically translated when displayed on the UI or a pre-translated string, e.g. `Edit`. Equivalent to a normal string in usage and functionality.

```
type TranslatableString = string & Translatable
```
