save_picture.ino 1.5 KB

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