> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/permission/album.md).

# 相册

{% hint style="info" %}
**需要设置权限**

`fetchAlbumItems`在使用前需要设置相册权限。请先查看权限设置指南。
{% endhint %}

***

### 1. 选择相册媒体

**SDK 函数：** `fetchAlbumItems`

这是一个从用户相册中选择照片·视频并获取的函数。可以同时选择照片和视频，用户取消选择时返回空数组 `[]`则返回。

**签名**

```typescript
function fetchAlbumItems(options?: FetchAlbumItemsOptions): Promise<AlbumItemResponse[]>;
```

**参数**

* **options** · `FetchAlbumItemsOptions`

  包含查询选项的对象。详细类型见下方 `FetchAlbumItemsOptions`。

**返回值**

* `Promise<AlbumItemResponse\[]>`

  返回所选媒体列表。用户取消时返回空数组。

**错误**

| 错误代码                      | 发生条件                      |
| ------------------------- | ------------------------- |
| `NOT_ALLOWED`             | 当未允许访问相册时                 |
| `INVALID_REQUEST`         | 当请求参数不正确时                 |
| `INVALID_DATA`            | 当媒体数据无效时                  |
| `UNSUPPORTED_APP_VERSION` | 当 Toss App 版本低于 5.261.0 时 |

**示例**

{% tabs %}
{% tab title="React" %}

```tsx
import { fetchAlbumItems } from '@apps-in-toss/web-framework';

async function pickMedia() {
  try {
    const items = await fetchAlbumItems({
      types: ['PHOTO', 'VIDEO'],
      maxCount: 5,
      base64: true,
    });

    if (items.length === 0) {
      console.log('已取消选择。');
      return;
    }

    items.forEach((item) => {
      console.log(item.type, item.id);
    });
  } catch (error) {
    console.error('相册查询错误：', error.code);
  }
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { fetchAlbumItems } from '@apps-in-toss/framework';

async function pickMedia() {
  try {
    const items = await fetchAlbumItems({
      types: ['PHOTO', 'VIDEO'],
      maxCount: 5,
      base64: true,
    });

    if (items.length === 0) {
      console.log('已取消选择。');
      return;
    }

    items.forEach((item) => {
      console.log(item.type, item.id);
    });
  } catch (error) {
    console.error('相册查询错误：', error.code);
  }
}
```

{% endtab %}
{% endtabs %}

**`FetchAlbumItemsOptions`**

```typescript
interface FetchAlbumItemsOptions {
  types?: AlbumItemType[];
  maxCount?: number;
  maxWidth?: number;
  base64?: boolean;
}
```

属性：

* typesArray<'PHOTO' | 'VIDEO'>

  要获取的媒体类型列表。 `'PHOTO'`（照片）， `'VIDEO'`（视频）中选择。如果不指定，则只获取照片。
* **maxCountnumber** · `10`

  要获取的项目最大数量。
* **maxWidthnumber** · `1024`

  图片的最大宽度。单位为像素。
* **base64boolean** · `false`

  图片的 `dataUri`是否将其作为 Base64 字符串返回。

**`AlbumItemResponse`**

```typescript
interface AlbumItemResponse {
  id: string;
  dataUri: string;
  type: AlbumItemType;
}
```

属性：

* idstring

  是项目的唯一 ID。
* **数据** · `Uristring`

  是媒体数据 URI。 `类型`如果是 `PHOTO`并且是 `base64` 选项 `true`则返回为 Base64 字符串。
* type'PHOTO' | 'VIDEO'

  是媒体类型。

***

### 2. 获取相册

**SDK 函数：** `fetchAlbumPhotos`

{% hint style="info" %}
**有新版本**

`fetchAlbumPhotos`仅支持照片。若需同时选择照片和视频，或需要更细致的控制， [`fetchAlbumItems`](#_1-%EC%95%A8%EB%B2%94-%EB%AF%B8%EB%94%94%EC%96%B4-%EC%84%A0%ED%83%9D%ED%95%98%EA%B8%B0)请使用。
{% endhint %}

这是一个从用户相册中获取照片列表的函数。可以设置最大数量和分辨率。

**签名**

```typescript
function fetchAlbumPhotos(options: { maxCount: number; maxWidth: number; base64: boolean }): Promise<ImageResponse[]>;
```

**参数**

* **options** · 必填

  包含查询选项的对象。

  * **options.maxCount** · `number`

    要获取的照片最大数量。
  * **options.maxWidth** · `number`

    照片的最大宽度。单位为像素。
  * **options.base64** · `boolean`

    设置是否将图片以 Base64 格式返回。

**返回值**

* `Promise<ImageResponse\[]>`

  返回包含相册照片唯一 ID 和数据 URI 的数组。

**示例**

{% tabs %}
{% tab title="Web（JS）" %}

```js
import { fetchAlbumPhotos, FetchAlbumPhotosPermissionError } from '@apps-in-toss/web-framework';

async function handleFetchAlbumPhotos() {
  try {
    const response = await fetchAlbumPhotos({ base64: true, maxWidth: 360 });
    response.forEach((image) => {
      const imageUri = 'data:image/jpeg;base64,' + image.dataUri;
      console.log('图片 URI：', imageUri);
    });
  } catch (error) {
    if (error instanceof FetchAlbumPhotosPermissionError) {
      console.log('没有相册读取权限');
    }
  }
}
```

{% endtab %}

{% tab title="Web（React）" %}

```tsx
import { fetchAlbumPhotos, FetchAlbumPhotosPermissionError, ImageResponse } from '@apps-in-toss/web-framework';
import { useState } from 'react';

function AlbumPhotoList() {
  const [albumPhotos, setAlbumPhotos] = useState<ImageResponse[]>([]);

  const handlePress = async () => {
    try {
      const response = await fetchAlbumPhotos({ base64: true, maxWidth: 360 });
      setAlbumPhotos((prev) => [...prev, ...response]);
    } catch (error) {
      if (error instanceof FetchAlbumPhotosPermissionError) {
        // 没有相册读取权限
      }
    }
  };

  return (
    <div>
      {albumPhotos.map((image) => {
        const imageUri = 'data:image/jpeg;base64,' + image.dataUri;
        return <img src={imageUri} key={image.id} />;
      })}
      <button onClick={handlePress}>获取相册</button>

  );
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { fetchAlbumPhotos, FetchAlbumPhotosPermissionError, ImageResponse } from '@apps-in-toss/framework';
import { useState } from 'react';
import { Alert, Button, Image, View } from 'react-native';

function AlbumPhotoList() {
  const [albumPhotos, setAlbumPhotos] = useState<ImageResponse[]>([]);

  const handlePress = async () => {
    try {
      const response = await fetchAlbumPhotos({ base64: true, maxWidth: 360 });
      setAlbumPhotos((prev) => [...prev, ...response]);
    } catch (error) {
      if (error instanceof FetchAlbumPhotosPermissionError) {
        // 没有相册读取权限
      }
    }
  };

  return (
    <View>
      {albumPhotos.map((image) => {
        const imageUri = 'data:image/jpeg;base64,' + image.dataUri;
        return <Image source={{ uri: imageUri }} key={image.id} />;
      })}
      <Button title="获取相册" onPress={handlePress} />
      <Button
        title="检查权限"
        onPress={async () => {
          const permission = await fetchAlbumPhotos.getPermission();
          Alert.alert(permission);
        }}
      />
      <Button
        title="请求权限"
        onPress={async () => {
          const permission = await fetchAlbumPhotos.openPermissionDialog();
          Alert.alert(permission);
        }}
      />
    </View>
  );
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/permission/album.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
