You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置Expo Camera拍摄照片的画质?(React Native+Express.js场景)

Expo Camera 调整照片画质的代码示例

核心配置说明

你可以通过CameraPictureOptions中的参数控制照片画质与文件大小,最常用的参数包括:

  • quality: 取值范围0-1,0为最低画质,1为最高画质,直接影响文件体积
  • maxWidth/maxHeight: 限制照片的最大分辨率,超出会自动缩放,有效降低高像素手机的照片大小
  • compress: Android平台额外的压缩比例(可选)

完整React Native组件示例

import { useState, useRef, useEffect } from 'react';
import { Button, View, Text } from 'react-native';
import { Camera, CameraType } from 'expo-camera';

export default function CameraCaptureScreen() {
  const [hasPermission, setHasPermission] = useState(null);
  const [cameraType, setCameraType] = useState(CameraType.back);
  const cameraRef = useRef(null);

  // 请求相机权限
  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  // 带画质配置的拍照函数
  const capturePhoto = async () => {
    if (!cameraRef.current) return;

    // 配置拍照参数,按需调整
    const pictureConfig = {
      quality: 0.4, // 推荐0.3-0.6,平衡画质与文件大小
      maxWidth: 1920, // 限制最大宽度为1080P级别
      maxHeight: 1080,
      skipProcessing: false, // 保持Expo的默认处理,确保兼容性
      // base64: true, // 若需要Base64格式可开启,注意内存占用
    };

    const photo = await cameraRef.current.takePictureAsync(pictureConfig);
    // 此处调用你的上传逻辑,将photo.uri发送到Express服务器
    console.log('照片文件信息:', { uri: photo.uri, size: photo.width * photo.height * 3 / 1024 / 1024 + 'MB' });
  };

  if (hasPermission === null) return <View />;
  if (hasPermission === false) return <Text>无相机访问权限</Text>;

  return (
    <View style={{ flex: 1 }}>
      <Camera style={{ flex: 1 }} type={cameraType} ref={cameraRef} />
      <View style={{ position: 'absolute', bottom: 40, alignSelf: 'center', gap: 10 }}>
        <Button title="拍照" onPress={capturePhoto} />
        <Button
          title="切换摄像头"
          onPress={() => setCameraType(cameraType === CameraType.back ? CameraType.front : CameraType.back)}
        />
      </View>
    </View>
  );
}

额外优化建议

  1. 服务器端配合:使用Express的multer中间件处理文件上传,避免直接接收大文件:
const express = require('express');
const multer = require('multer');
const app = express();

// 配置文件存储路径与文件名规则
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, './uploads'),
  filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`)
});
const upload = multer({ storage, limits: { fileSize: 5 * 1024 * 1024 } }); // 限制单文件不超过5MB

app.post('/upload', upload.single('photo'), (req, res) => {
  // 此处可将文件转存到云存储(如OSS、S3)或进行其他处理
  res.status(200).json({ success: true, file: req.file });
});

app.listen(3000, () => console.log('服务器运行于http://localhost:3000'));
  1. 上传前预览:可以通过Image组件预览photo.uri,确认画质符合需求后再上传。

内容的提问来源于stack exchange,提问作者Carsdan Dvorachek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:50:59