save_picture.ino 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. Serial.println("Camera capture failed");
  27. return;
  28. }
  29. if (!SD_MMC.begin())
  30. {
  31. // SD Card Mount Failed.
  32. Serial.println("SD Card Mount Failed");
  33. esp_camera_fb_return(frame_buffer);
  34. return;
  35. }
  36. // Generate a unique filename.
  37. String path = "/picture";
  38. path += String(millis());
  39. path += ".jpg";
  40. fs::FS &fs = SD_MMC;
  41. File file = fs.open(path.c_str(), FILE_WRITE);
  42. if (!file)
  43. {
  44. Serial.println("Failed to open file in writing mode");
  45. }
  46. else
  47. {
  48. if (file.write(frame_buffer->buf, frame_buffer->len) != frame_buffer->len)
  49. {
  50. Serial.println("Failed to write the image to the file");
  51. }
  52. file.close(); // Close the file in any case.
  53. }
  54. // Update framesize back to the default.
  55. cam->set_framesize(cam, FRAMESIZE_QQVGA);
  56. // Return the frame buffer back to the camera driver.
  57. esp_camera_fb_return(frame_buffer);
  58. }