---
name: "image"
mode: "component"
versionRequirements:
  - { name: "基础库", version: "2.10.0" }
title: "image - 图片"
---

## image

> [VERSION] 基础库 >= 2.10.0

### 描述

图片组件，支持多种裁剪和缩放模式。

### 属性

| 属性 | 类型 | 必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `src` | `string` | 是 | - | 图片地址 |
| `mode` | `string` | 否 | `"scaleToFill"` | 图片裁剪、缩放的模式 |
| `lazy-load` | `boolean` | 否 | `false` | 开启懒加载，滚动到可视区域后再加载图片 |
| `fade-duration` | `number` | 否 | `0` | 图片渐显动画时长，单位毫秒 |

#### 事件

| 事件名 | 类型 | 描述 |
| --- | --- | --- |
| `load` | `(event: ImageLoadEvent) => void` | 图片加载完成时触发 |
| `error` | `(event: ImageErrorEvent) => void` | 图片加载失败时触发 |

**ImageLoadEvent**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `type` | `"load"` | 事件类型 |
| `detail` | `ImageLoadDetail` | 事件数据 |

**ImageErrorEvent**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `type` | `"error"` | 事件类型 |
| `detail` | `ImageErrorDetail` | 事件数据 |

### 示例代码

#### 基础用法与缩放模式

*index.tyml*

```xml
<view class="wrap">
  <text class="title">scaleToFill（默认）</text>
  <image src="https://example.com/pic.jpg" mode="scaleToFill" class="img" />

  <text class="title">aspectFit</text>
  <image src="https://example.com/pic.jpg" mode="aspectFit" class="img" />

  <text class="title">aspectFill</text>
  <image src="https://example.com/pic.jpg" mode="aspectFill" class="img" />

  <text class="title">widthFix</text>
  <image src="https://example.com/pic.jpg" mode="widthFix" class="img-auto" />
</view>
```

*index.tyss*

```css
.wrap { padding: 20rpx; }
.title { font-size: 28rpx; color: #666; margin: 20rpx 0 10rpx; }
.img { width: 300rpx; height: 300rpx; background-color: #f0f0f0; }
.img-auto { width: 300rpx; }
```

*index.js*

```javascript
Page({});
```

#### 懒加载与事件处理

*index.tyml*

```xml
<view class="wrap">
  <image
    src="{{imgSrc}}"
    mode="widthFix"
    lazy-load="{{true}}"
    fade-duration="{{300}}"
    class="img"
    bindload="onLoad"
    binderror="onError"
  />
  <text ty:if="{{info}}">{{info}}</text>
</view>
```

*index.tyss*

```css
.wrap { padding: 20rpx; }
.img { width: 100%; }
```

*index.js*

```javascript
Page({
  data: {
    imgSrc: 'https://example.com/pic.jpg',
    info: '',
  },
  onLoad(e) {
    this.setData({
      info: '加载成功: ' + e.detail.width + 'x' + e.detail.height,
    });
  },
  onError(e) {
    this.setData({ info: '加载失败: ' + e.detail.errMsg });
  },
});
```


### 注意事项

- 部分低端机型对 WebP 的兼容性较差，可能出现图片无法显示或显示异常。建议优先使用兼容性更稳定的图片格式；如果必须使用 WebP，需要在目标机型上验证展示效果并准备兜底图片。

### 常见问题

#### image 支持懒加载吗？

支持，可通过配置`lazy-load`实现图片懒加载

#### 真机调用 image 组件，显示的图片被压缩？

建议把 mode 值设为 widthFix。

#### 图片地址的引入方式

- 网络图片：`src="https://tuya.com/img.png"`
  - 网络图片需要支持 HTTPS 协议
- base64 图片：`src="data:image/png;base64,xxx"`
- 绝对路径：`src="/assets/img.png"`
  - 绝对路径的 `/` 代表根目录, 如果配置了 `project.tuya.json` 中的 `miniprogramRoot` 字段，那么 `/` 代表的是 `miniprogramRoot` 的路径
- 相对路径：`src="./assets/img.png"` **(不推荐)**
  - 仅在页面内支持相对路径，自定义组件内不支持相对路径。
  - 相对路径是相对于当前文件的路径, 不推荐使用相对路径，因为相对路径会受到文件位置的影响，不利于维护。
