# Images

- Human documentation: [https://docs.univer.ai/guides/sheets/features/images](https://docs.univer.ai/guides/sheets/features/images)

- Agent Markdown: [https://docs.univer.ai/guides/sheets/features/images.md](https://docs.univer.ai/guides/sheets/features/images.md)

- Requested language: `en-US`

- Content language: `en-US`

- Documentation version: `1.0.0-rc.0`

- Source: [sheets/features/images.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/images.mdx)

---

#### Package metadata

```json
{
  "preset": [
    {
      "client": "@univerjs/preset-sheets-drawing",
      "locale": "@univerjs/preset-sheets-drawing/locales/en-US",
      "style": "@univerjs/preset-sheets-drawing/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs/drawing"
    },
    {
      "client": "@univerjs/drawing-ui",
      "locale": "@univerjs/drawing-ui/locale/en-US",
      "style": "@univerjs/drawing-ui/lib/index.css"
    },
    {
      "client": "@univerjs/sheets-drawing"
    },
    {
      "client": "@univerjs/sheets-drawing-ui",
      "facade": "@univerjs/sheets-drawing-ui/facade",
      "locale": "@univerjs/sheets-drawing-ui/locale/en-US",
      "style": "@univerjs/sheets-drawing-ui/lib/index.css"
    }
  ],
  "server": false
}
```

Images can be used to enrich spreadsheet content, enhance visual expression, and help illustrate or highlight key information.

Currently, the supported image types are: floating images and cell images.

> Interactive example: [Open the playground](/playground/sheets/images)

## Preset Mode

### Installation

#### npm

```bash
npm install @univerjs/preset-sheets-drawing
```

#### pnpm

```bash
pnpm add @univerjs/preset-sheets-drawing
```

#### yarn

```bash
yarn add @univerjs/preset-sheets-drawing
```

#### bun

```bash
bun add @univerjs/preset-sheets-drawing
```

### Usage

```typescript
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing' // [!code ++]
import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US' // [!code ++]
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'

import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css' // [!code ++]

const { univerAPI } = createUniver({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      UniverPresetSheetsCoreEnUS,
      UniverPresetSheetsDrawingEnUS, // [!code ++]
    ),
  },
  presets: [
    UniverSheetsCorePreset(),
    UniverSheetsDrawingPreset(), // [!code ++]
  ],
})
```

If you are using the [Collaboration](https://docs.univer.ai/guides/sheets/features/collaboration.md) feature, make sure to pass the `collaboration: true` option in `UniverSheetsDrawingPreset`:

```typescript
UniverSheetsDrawingPreset({
  collaboration: true, // [!code ++]
})
```

### Presets and Configuration

```typescript
interface IUniverSheetsDrawingPresetConfig {
  /**
   * Whether use the collaboration feature.
   * @default false
   */
  collaboration?: boolean
  /**
   * The maximum allowed size of uploaded images in bytes.
   * @default 5 * 1024 * 1024 (5MB)
   */
  allowImageSize?: number
}
```

## Plugin Mode

### Installation

#### npm

```bash
npm install @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui
```

#### pnpm

```bash
pnpm add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui
```

#### yarn

```bash
yarn add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui
```

#### bun

```bash
bun add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui
```

### Usage

```typescript
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'
import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing' // [!code ++]
import { IImageIoService, UniverDrawingPlugin } from '@univerjs/drawing' // [!code ++]
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui' // [!code ++]
import DrawingUIEnUS from '@univerjs/drawing-ui/locale/en-US' // [!code ++]
import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing' // [!code ++]
import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui' // [!code ++]
import SheetsDrawingUIEnUS from '@univerjs/sheets-drawing-ui/locale/en-US' // [!code ++]

import '@univerjs/drawing-ui/lib/index.css' // [!code ++]
import '@univerjs/sheets-drawing-ui/lib/index.css' // [!code ++]

import '@univerjs/sheets-drawing/facade' // [!code ++]
import '@univerjs/sheets-drawing-ui/facade' // [!code ++]

const univer = new Univer({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      DrawingUIEnUS, // [!code ++]
      SheetsDrawingUIEnUS, // [!code ++]
    ),
  },
})

univer.registerPlugin(UniverDrawingPlugin) // [!code ++]
univer.registerPlugin(UniverDrawingUIPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsDrawingPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsDrawingUIPlugin) // [!code ++]
```

If you are using the [Collaboration](https://docs.univer.ai/guides/docs/features/collaboration.md) feature, you need to add the `override` configuration:

```typescript
univer.registerPlugin(UniverDrawingPlugin, {
  override: [[IImageIoService, null]], // [!code ++]
  // allowImageSize: 20 * 1024 * 1024, // set the maximum allowed size of uploaded images to 20MB, optional
})
```

### Plugins and Configuration

```typescript
interface IUniverDrawingConfig {
  /**
   * The maximum allowed size of uploaded images in bytes.
   * @default 5 * 1024 * 1024 (5MB)
   */
  allowImageSize?: number
}
```

## Facade API

Complete Facade API type definitions can be found in the [FacadeAPI](https://reference.univer.ai/en-US).

### Importing

> [!INFO: Plugin mode note]
> Only plugin mode requires manually importing the Facade package. Preset mode already includes the corresponding Facade package, so no extra import is needed.

```typescript
import '@univerjs/sheets-drawing/facade'
import '@univerjs/sheets-drawing-ui/facade'
```

### Add Floating DOM

`FWorksheet.addFloatDomToPosition(layer)` method can add a floating DOM element to a specified position.

```tsx
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()

// You should register components at an appropriate time (e.g., when Univer is loaded)
// This is a React component. For Vue3 components, the third parameter should be `{ framework: 'vue3' }`
univerAPI.registerComponent(
  'myFloatDom',
  ({ data }) => (
    <div style={{ width: '100%', height: '100%', background: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' }}>
      popup content:
      {' '}
      {data?.label}
    </div>
  ),
)

// Add a floating DOM
// If disposable is null, floating DOM addition failed
const disposable = fWorksheet.addFloatDomToPosition({
  componentKey: 'myFloatDom',
  initPosition: {
    startX: 100,
    endX: 300,
    startY: 100,
    endY: 200,
  },

  // Component data
  data: {
    label: 'hahah',
  },
})

// 2 秒后移除浮动 DOM
setTimeout(() => {
  disposable?.dispose()
}, 2000)
```

`FWorksheet.addFloatDomToRange(range, layer, domLayout)` method can add a floating DOM element to a specified range.

```tsx
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()

// Register a range loading component
function RangeLoading() {
  const divStyle = {
    width: '100%',
    height: '100%',
    backgroundColor: '#fff',
    border: '1px solid #ccc',
    boxSizing: 'border-box' as const,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    textAlign: 'center' as const,
    transformOrigin: 'top left',
  }

  return (
    <div style={divStyle}>
      Loading...
    </div>
  )
}
univerAPI.registerComponent('RangeLoading', RangeLoading)

// Add the range loading component covering the range A1:C3
const fRange = fWorksheet.getRange('A1:C3')
const disposable = fWorksheet.addFloatDomToRange(fRange, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading')

// Remove the floating DOM after 2 seconds
setTimeout(() => {
  disposable?.dispose()
}, 2000)

// another example-------------------
// Register a float button component
function FloatButton() {
  const divStyle = {
    width: '100px',
    height: '30px',
    backgroundColor: '#fff',
    border: '1px solid #ccc',
    boxSizing: 'border-box' as const,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    textAlign: 'center' as const,
    cursor: 'pointer',
  }

  const clickHandler = () => {
    console.warn('click')
  }

  return (
    <div style={divStyle} onClick={clickHandler}>
      FloatButton
    </div>
  )
}
univerAPI.registerComponent('FloatButton', FloatButton)

// Add the float button to the range A5:C7, position is start from A5 cell, and width is 100px, height is 30px, margin is 100% of range width and height
const fRange2 = fWorksheet.getRange('A5:C7')
const disposable2 = fWorksheet.addFloatDomToRange(
  fRange2,
  {
    componentKey: 'FloatButton',
  },
  {
    width: 100,
    height: 30,
    marginX: '100%', // margin percent to range width, or pixel
    marginY: '100%',
  },
  'myFloatButton',
)
```

`FWorksheet.addFloatDomToColumnHeader(column, layer, domPos)` method can add a floating DOM element to a specified column header.

```tsx
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()

// Register a float button component
function FloatButton() {
  const divStyle = {
    width: '100px',
    height: '30px',
    backgroundColor: '#fff',
    border: '1px solid #ccc',
    boxSizing: 'border-box' as const,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    textAlign: 'center' as const,
    cursor: 'pointer',
  }

  const clickHandler = () => {
    console.warn('click')
  }

  return (
    <div style={divStyle} onClick={clickHandler}>
      FloatButton
    </div>
  )
}
univerAPI.registerComponent('FloatButton', FloatButton)

// Add the float button to the column D header, position is right align, width is 100px, height is 30px, margin is 0
const disposable = fWorksheet.addFloatDomToColumnHeader(
  3,
  {
    componentKey: 'FloatButton',
    allowTransform: false,
  },
  {
    width: 100,
    height: 30,
    marginX: 0,
    marginY: 0,
    horizonOffsetAlign: 'right',
  },
  'myFloatButton',
)

// Remove the float button after 2 seconds
setTimeout(() => {
  disposable?.dispose()
}, 2000)
```

### Insert Floating Images

[`FWorksheet.newOverGridImage()`](https://docs.univer.ai/reference/facade/worksheet.md#newovergridimage) creates a floating image builder, returns an instance of `FOverGridImageBuilder`, and generates an `ISheetImage` object for inserting floating images through chain calls.

Here are some member methods on [`FOverGridImageBuilder`](https://docs.univer.ai/reference/facade/chart.md):

| Method          | Description                                                                                                                   |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| buildAsync      | Build the image and return `ISheetImage` object                                                                               |
| setSource       | Set the source of the image                                                                                                   |
| setColumn       | Set the horizontal position of the image                                                                                      |
| setRow          | Set the vertical position of the image                                                                                        |
| setColumnOffset | Set the horizontal offset of the image                                                                                        |
| setRowOffset    | Set the vertical offset of the image                                                                                          |
| setWidth        | Set the width of the image                                                                                                    |
| setHeight       | Set the height of the image                                                                                                   |
| setAnchorType   | Set the anchor type of the image, whether the position and size change with the cell                                          |
| setCropTop      | Set the cropping region of the image by defining the top edges, thereby displaying the specific part of the image you want    |
| setCropLeft     | Set the cropping region of the image by defining the left edges, thereby displaying the specific part of the image you want   |
| setCropBottom   | Set the cropping region of the image by defining the bottom edges, thereby displaying the specific part of the image you want |
| setCropRight    | Set the cropping region of the image by defining the right edges, thereby displaying the specific part of the image you want  |
| setRotate       | Set the rotation angle of the image                                                                                           |

```typescript
// create a new image builder and set image source.
// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300px
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const image = await fWorksheet.newOverGridImage()
  .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
  .setColumn(5)
  .setRow(5)
  .setWidth(500)
  .setHeight(300)
  .buildAsync()
fWorksheet.insertImages([image])
```

Also can insert image by `FWorksheet.insertImage(url, column, row, offsetX, offsetY)` method.

```typescript
// Insert an image to the sheet, position is F6, offset is 10px
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()
const result = await fWorksheet.insertImage('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', 5, 5, 10, 10)
```

### Get Floating Images

`FWorksheet.getImages()` method can get all floating images in the worksheet, and return an array of [`FOverGridImage[]`](https://docs.univer.ai/reference/facade/chart.md) instances.

```typescript
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()
const images = fWorksheet.getImages()
images.forEach((image) => {
  image.getId()
})
```

You can also get a floating image by its ID using the `FWorksheet.getImageById(id)` method.

### Update Floating Images

`FWorksheet.updateImages(sheetImages)` method can update the position and size of floating images. etc.

```typescript
// create a new image builder and set image source.
// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300px
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const image = await fWorksheet.newOverGridImage()
  .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
  .setColumn(5)
  .setRow(5)
  .setWidth(500)
  .setHeight(300)
  .buildAsync()
fWorksheet.insertImages([image])

// update the image width to 100px and height to 50px after 4 seconds
setTimeout(async () => {
  const imageBuilder = fWorksheet.getImageById(image.drawingId).toBuilder()
  const newImage = await imageBuilder.setWidth(100).setHeight(50).buildAsync()
  fWorksheet.updateImages([newImage])
}, 4000)
```

### Delete Floating Images

`FWorksheet.deleteImages(sheetImages)` method can delete floating images.

```typescript
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()
const image = fWorksheet.getImages()[0]

// Delete the first image of the sheet
fWorksheet.deleteImages([image])
```

### Insert Cell Images

`FRange.insertCellImageAsync(file)` method can insert cell images.

```typescript
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Insert an image into the cell A10
const fRange = fWorksheet.getRange('A10')
const result = await fRange.insertCellImageAsync('https://avatars.githubusercontent.com/u/61444807?s=48&v=4')
```
