save_picture.ino 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "save_picture.h"
  2. void save_picture()
  3. {
  4. sensor_t *cam = esp_camera_sensor_get();
  5. // Check if the sensor is valid.
  6. if (!cam)
  7. {
  8. Serial.println("Failed to acquire camera sensor");
  9. return;
  10. }
  11. // Set pixel format to JPEG for saving picture.
  12. cam->set_pixformat(cam, PIXFORMAT_JPEG);
  13. // Set frame size based on available PSRAM.
  14. if (psramFound())
  15. {
  16. cam->set_framesize(cam, FRAMESIZE_UXGA);
  17. }
  18. else
  19. {
  20. cam->set_framesize(cam, FRAMESIZE_SVGA);
  21. }
  22. // Get a frame buffer from camera.
  23. camera_fb_t *frame_buffer = esp_camera_fb_get();
  24. if (!frame_buffer)
  25. {
  26. // Camera capture failed
  27. return;
  28. }
  29. if (!SD_MMC.begin())
  30. {
  31. // SD Card Mount Failed.
  32. esp_camera_fb_return(frame_buffer);
  33. return;
  34. }
  35. // Generate a unique filename.
  36. String path = "/picture";
  37. path += String(millis());
  38. path += ".jpg";
  39. fs::FS &fs = SD_MMC;
  40. File file = fs.open(path.c_str(), FILE_WRITE);
  41. if (!file)
  42. {
  43. // Failed to open file in writing mode
  44. }
  45. else
  46. {
  47. if (file.write(frame_buffer->buf, frame_buffer->len) != frame_buffer->len)
  48. {
  49. // Failed to write the image to the file
  50. }
  51. file.close(); // Close the file in any case.
  52. }
  53. // Update framesize back to the default.
  54. cam->set_framesize(cam, FRAMESIZE_QQVGA);
  55. // Return the frame buffer back to the camera driver.
  56. esp_camera_fb_return(frame_buffer);
  57. }