> 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/camera.md).

# 相机

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

`openCamera`在使用之前，需要设置相机权限。请先查看权限设置指南。
{% endhint %}

### 拍照

**SDK 函数：** `openCamera`

这是一个启动相机并返回拍摄图像的函数。

**签名**

```typescript
function openCamera(options: { base64: boolean; maxWidth: number }): Promise<ImageResponse>;
```

**参数**

* **options** · 必需 · `OpenCameraOptions`

  这是在启动相机时使用的选项对象。

  * **options.base64** · `boolean`

    表示是否以 Base64 格式返回图像的布尔值。默认值为 `false`。 `true`设置为 `dataUri` 而是返回 Base64 编码字符串。
  * **options.maxWidth** · `number`

    表示图像最大宽度的数字值。默认值为 `1024`。

**属性**

* openPermissionDialog

  显示重新请求相机访问权限的对话框。用户可以在“允许”、“仅允许一次”、“不允许”中选择其一。如果选择“允许”或“仅允许一次” `allowed`返回 `denied`会返回。
* getPermission

  返回相机访问权限的当前状态。 `allowed`表示用户已允许相机访问权限。 `denied`表示用户已拒绝相机访问权限。 `notDetermined`表示从未请求过相机访问权限。

如果在 Toss 应用设置中相机权限被拒绝， `osPermissionDenied`会返回。

**返回值**

* `Promise<ImageResponse>`

返回包含拍摄图像信息的对象。返回对象的组成如下：

* `id`: 图像的唯一标识符。
* `dataUri`: 表示图像数据的数据 URI。

### 相机权限错误

**错误类型：** `OpenCameraPermissionError`

这是在相机权限被拒绝时发生的错误。发生错误时 `error instanceof OpenCameraPermissionError`可以通过它确认。

**签名**

```typescript
class OpenCameraPermissionError extends PermissionError {
  constructor();
}
```

**示例**

**启动相机后获取拍摄的照片**

这是使用相机拍照并获取结果的示例。在此过程中，可以确认当前相机权限状态，如果没有权限则请求权限。如果用户拒绝了权限或系统限制了权限，则 `OpenCameraPermissionError`会返回。

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

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

const base64 = true;

async function handleOpenCamera() {
  try {
    const response = await openCamera({ base64 });
    const imageUri = base64 ? 'data:image/jpeg;base64,' + response.dataUri : response.dataUri;
    console.log('拍照成功:', imageUri);
  } catch (error) {
    if (error instanceof OpenCameraPermissionError) {
      console.log('权限错误');
    }
    console.error('获取照片失败：', error);
  }
}

async function handleGetPermissionForOpenCamera() {
  const permission = await openCamera.getPermission();
  return permission;
}

async function handleOpenPermissionDialogForOpenCamera() {
  const permission = await openCamera.openPermissionDialog();
  return permission;
}
```

{% endtab %}

{% tab title="React" %}

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

const base64 = true;

// 启动相机并在屏幕上显示拍摄图像的组件
function Camera() {
  const [image, setImage] = useState<ImageResponse | null>(null);

  const handlePress = async () => {
    try {
      const response = await openCamera({ base64 });
      setImage(response);
    } catch (error) {
      if (error instanceof OpenCameraPermissionError) {
        console.log('权限错误');
      }

      console.error('获取照片失败：', error);
    }
  };

  // 若要显示以 base64 格式返回的图像，需要添加数据 URL scheme 前缀。
  const imageUri = base64 ? 'data:image/jpeg;base64,' + image?.dataUri : image?.dataUri;

  return (
    <div>
      {image ? <Image source={{ uri: imageUri }} style={{ width: 200, height: 200 }} /> : <span>没有照片</span>}
      <input type="button" value="拍照" onClick={handlePress} />
      <input
        type="button"
        value="查看权限"
        onClick={async () => {
          const permission = await openCamera.getPermission();
          Alert.alert(permission);
        }}
      />

      <input
        type="button"
        value="请求权限"
        onClick={async () => {
          const currentPermission = await openCamera.openPermissionDialog();
          Alert.alert(currentPermission);
        }}
      />

  );
}
```

{% endtab %}

{% tab title="React Native" %}

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

const base64 = true;

// 启动相机并在屏幕上显示拍摄图像的组件
function Camera() {
  const [image, setImage] = useState<ImageResponse | null>(null);

  const handlePress = async () => {
    try {
      const response = await openCamera({ base64 });
      setImage(response);
    } catch (error) {
      if (error instanceof OpenCameraPermissionError) {
        console.log('权限错误');
      }

      console.error('获取照片失败：', error);
    }
  };

  // 若要显示以 base64 格式返回的图像，需要添加数据 URL scheme 前缀。
  const imageUri = base64 ? 'data:image/jpeg;base64,' + image?.dataUri : image?.dataUri;

  return (
    <View>
      {image ? <Image source={{ uri: imageUri }} style={{ width: 200, height: 200 }} /> : <Text>没有照片</Text>}
      <Button title="拍照" onPress={handlePress} />
      <Button
        title="查看权限"
        onPress={async () => {
          const permission = await openCamera.getPermission();
          Alert.alert(permission);
        }}
      />

      <Button
        title="请求权限"
        onPress={async () => {
          const currentPermission = await openCamera.openPermissionDialog();
          Alert.alert(currentPermission);
        }}
      />
    </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/camera.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.
