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

替换react-native-camera为react-native-vision-camera:添加叠加图及压缩拍摄图片

替换react-native-camera为react-native-vision-camera的问题解决方案

1. 实现拍摄时的叠加图片功能

react-native-vision-camera没有内置的叠加图API,直接通过React Native的View层级嵌套就能实现——把Camera组件作为底层,叠加的Image放在同一个父View里,通过绝对定位覆盖在相机预览上层即可。

关键实现要点:

  • 用StyleSheet.absoluteFillObject让叠加图占满整个相机预览区域,再按需调整位置、尺寸
  • 叠加图的resizeMode要和相机预览的比例匹配(比如相机用preset="photo"时预览为4:3,叠加图可设resizeMode="contain"或"cover")

代码片段:

import { View, Image, StyleSheet, Button } from 'react-native';
import { Camera, useCameraDevice, useCameraPermissions } from 'react-native-vision-camera';
import { useRef, useEffect } from 'react';

function CameraScreen() {
  const device = useCameraDevice('back');
  const { hasPermission, requestPermission } = useCameraPermissions();
  const cameraRef = useRef(null);

  useEffect(() => {
    if (!hasPermission) requestPermission();
  }, [hasPermission]);

  if (!device || !hasPermission) return <View />;

  return (
    <View style={styles.container}>
      {/* 相机预览组件 */}
      <Camera
        ref={cameraRef}
        style={styles.camera}
        device={device}
        isActive={true}
        preset="photo"
      />
      {/* 叠加图片 */}
      <Image
        style={styles.overlay}
        source={require('./assets/overlay-watermark.png')}
        resizeMode="contain"
      />
      <Button
        title="拍摄"
        onPress={() => takePhoto(cameraRef)}
        style={styles.shootBtn}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  camera: {
    flex: 1,
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    opacity: 0.6, // 可选:调整叠加图透明度
  },
  shootBtn: {
    position: 'absolute',
    bottom: 30,
    alignSelf: 'center',
  },
});

2. 拍摄图片的压缩与质量控制

react-native-vision-camera的takePhoto方法提供了photoOptions参数,通过以下配置实现压缩:

  • quality: 0-1之间的数值,1为无损,数值越小压缩率越高
  • format: 指定图片格式,"jpeg"支持质量压缩(默认格式),"png"不支持质量压缩
  • resize: 设置输出图片的宽高,缩小分辨率可直接减小文件体积

代码片段:

async function takePhoto(cameraRef) {
  if (!cameraRef.current) return;

  try {
    const compressedPhoto = await cameraRef.current.takePhoto({
      quality: 0.6, // 兼顾清晰度与体积的中间值,按需调整
      format: 'jpeg',
      resize: {
        width: 1280, // 输出宽度,匹配相机4:3比例
        height: 960,
      },
      saveToGallery: true, // 可选:保存到系统相册
    });

    // 查看压缩后图片大小(字节)
    console.log('压缩后图片大小:', await compressedPhoto.file.size);
    // compressedPhoto.file.uri 为压缩后图片的本地路径
  } catch (error) {
    console.error('拍照失败:', error);
  }
}

内容的提问来源于stack exchange,提问作者Waseem Kurne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:55:10