WebcamCapture.jsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import {useRef, useState, useCallback} from 'react';
  2. import Webcam from "react-webcam";
  3. import {Button} from '@mui/material';
  4. import { fileMessage } from '../../../../reducers/messageReducer';
  5. import { useDispatch } from 'react-redux';
  6. import { getUserAvatar } from '../../../../reducers/userDataReducer';
  7. const WebcamCapture = () => {
  8. const dispatch = useDispatch();
  9. const webcamRef = useRef(null);
  10. const [imgSrc, setImgSrc] = useState(null);
  11. const sendPhotoToChat = async (imageStream) => {
  12. const blob = await fetch(imageStream).then((res) => res.blob());
  13. dispatch(fileMessage(blob))
  14. }
  15. const savePhotoToAvatar = async (imageStream) => {
  16. const blob = await fetch(imageStream).then((res) => res.blob());
  17. dispatch(getUserAvatar(blob))
  18. }
  19. const capture = useCallback(async () => {
  20. const imageSrc = webcamRef.current.getScreenshot();
  21. setImgSrc(imageSrc);
  22. }, [webcamRef, setImgSrc]);
  23. return (
  24. <div style={{
  25. 'maxHeight': '350px',
  26. 'maxWidth': '350px',
  27. 'position': 'absolute',
  28. 'top': '10%',
  29. "left": '10%',
  30. 'zIndex': 9999,
  31. }}>
  32. <Webcam
  33. audio={false}
  34. ref={webcamRef}
  35. screenshotFormat="image/jpeg"
  36. style={{
  37. 'maxHeight': '350px',
  38. 'maxWidth': 'auto'
  39. }}
  40. />
  41. <Button
  42. onClick={capture}
  43. variant="contained"
  44. component="label"
  45. >
  46. New photo
  47. </Button> {imgSrc && (
  48. <>
  49. <Button
  50. variant="contained"
  51. component="label"
  52. onClick={() => sendPhotoToChat(imgSrc)}
  53. >
  54. Send
  55. </Button>
  56. <Button
  57. variant="contained"
  58. component="label"
  59. onClick={() => savePhotoToAvatar(imgSrc)}
  60. >
  61. Save avatar
  62. </Button>
  63. <img
  64. src={imgSrc}
  65. style={{
  66. 'border':'4px solid blue',
  67. 'borderRadius': '10px'
  68. }}
  69. />
  70. </>
  71. )}
  72. </div>
  73. );
  74. };
  75. export default WebcamCapture;