Picmonkey API get display and save image to email form

Learn picmonkey api get display and save image to email form with practical examples, diagrams, and best practices. Covers html development techniques with visual explanations.

Integrating PicMonkey API for Image Display and Email Saving

Hero image for Picmonkey API get display and save image to email form

Learn how to integrate the PicMonkey API into your web application to allow users to edit images, display the edited results, and save them directly to an email form for submission.

The PicMonkey API provides a powerful way to embed image editing capabilities directly into your web application. This article will guide you through the process of setting up the PicMonkey editor, handling the edited image callback, displaying the result, and finally, preparing the image data to be sent via an email form. This integration is particularly useful for applications requiring user-generated content or personalized image submissions.

Setting Up the PicMonkey Editor and Callback

To begin, you need to initialize the PicMonkey editor and configure it to call back to your application once an image has been edited. The PicMonkey API uses a JavaScript-based approach, where you embed a script and then call a function to open the editor. The crucial part is defining a callback URL or function that PicMonkey will invoke, passing the edited image data back to your server or client-side script.

<script type="text/javascript" src="//assets.picmonkey.com/js/picmonkey-1.0.js"></script>
<script type="text/javascript">
  function launchPicMonkey() {
    PicMonkey.launch({
      apiKey: 'YOUR_API_KEY',
      url: 'https://example.com/path/to/your/initial-image.jpg', // Optional: initial image URL
      onSave: 'handlePicMonkeySave',
      onClose: 'handlePicMonkeyClose',
      saveUrl: 'https://example.com/picmonkey-save-endpoint',
      saveUrlAccessKey: 'YOUR_ACCESS_KEY' // If using saveUrl
    });
  }

  function handlePicMonkeySave(data) {
    // This function is called when the user clicks 'Save' in PicMonkey
    // 'data' object contains information about the saved image
    console.log('PicMonkey Save Data:', data);
    // Typically, data.url will contain the URL of the saved image
    // or data.base64 will contain the image as a base64 string if configured.
    displayEditedImage(data.url || data.base64);
  }

  function handlePicMonkeyClose() {
    console.log('PicMonkey editor closed.');
  }

  // Call launchPicMonkey() when a button is clicked, for example
  // document.getElementById('editImageButton').addEventListener('click', launchPicMonkey);
</script>
<button id="editImageButton" onclick="launchPicMonkey()">Edit Image with PicMonkey</button>

Basic PicMonkey editor initialization and callback setup.

Displaying the Edited Image and Preparing for Email

Once the handlePicMonkeySave callback receives the edited image data, you'll want to display it to the user and prepare it for submission via an email form. The image data can come as a URL (if PicMonkey saved it to your saveUrl endpoint) or as a Base64 encoded string. For email forms, embedding the image as a Base64 string within a hidden input field is a common approach, as direct file uploads via client-side JavaScript to email forms are not standard.

flowchart TD
    A[User Clicks 'Edit Image'] --> B{Launch PicMonkey Editor};
    B --> C[User Edits Image];
    C --> D{User Clicks 'Save'}; 
    D --> E["PicMonkey Calls `handlePicMonkeySave`"];
    E --> F{Receive Image Data (URL or Base64)};
    F --> G[Display Edited Image on Page];
    G --> H[Populate Hidden Form Field with Image Data];
    H --> I[User Submits Email Form];
    I --> J[Server Processes Form & Sends Email];

Workflow for editing, displaying, and preparing an image for email submission.

<img id="editedImageDisplay" src="" alt="Edited Image" style="max-width: 100%; display: none;">
<form id="emailForm" action="/send-email" method="POST">
  <input type="hidden" name="editedImageData" id="editedImageDataInput">
  <label for="recipientEmail">Recipient Email:</label>
  <input type="email" id="recipientEmail" name="recipientEmail" required>
  <label for="emailSubject">Subject:</label>
  <input type="text" id="emailSubject" name="emailSubject" value="Your Edited Image" required>
  <button type="submit">Send Email with Image</button>
</form>

<script type="text/javascript">
  function displayEditedImage(imageData) {
    const imgElement = document.getElementById('editedImageDisplay');
    const dataInput = document.getElementById('editedImageDataInput');

    if (imageData) {
      if (imageData.startsWith('http')) {
        // It's a URL
        imgElement.src = imageData;
        dataInput.value = imageData; // Store URL if server handles fetching
      } else if (imageData.startsWith('data:image')) {
        // It's a Base64 string
        imgElement.src = imageData;
        dataInput.value = imageData; // Store Base64 string
      }
      imgElement.style.display = 'block';
    } else {
      imgElement.style.display = 'none';
      dataInput.value = '';
    }
  }

  // Example of how handlePicMonkeySave would call this:
  // function handlePicMonkeySave(data) {
  //   displayEditedImage(data.url || data.base64);
  // }
</script>

HTML structure for displaying the image and an email form with a hidden input for image data.

Server-Side Handling for Email Submission

When the email form is submitted, your server-side endpoint (/send-email in the example) will receive the editedImageData (either a URL or a Base64 string) along with other form fields. On the server, you'll need to process this data. If it's a URL, you might fetch the image from that URL. If it's a Base64 string, you'll decode it. Then, you can attach this image to an email using your preferred email sending library or service.

// Example using Node.js with Express and Nodemailer
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const axios = require('axios'); // For fetching image from URL

const app = express();
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); // Increase limit for base64 images

// Configure Nodemailer transporter
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your_email@gmail.com',
    pass: 'your_email_password' // Use environment variables for production!
  }
});

app.post('/send-email', async (req, res) => {
  const { recipientEmail, emailSubject, editedImageData } = req.body;

  if (!editedImageData) {
    return res.status(400).send('No image data provided.');
  }

  let attachments = [];
  try {
    if (editedImageData.startsWith('http')) {
      // Fetch image from URL
      const response = await axios.get(editedImageData, { responseType: 'arraybuffer' });
      attachments.push({
        filename: 'edited_image.jpg',
        content: Buffer.from(response.data, 'binary'),
        contentType: response.headers['content-type'] || 'image/jpeg'
      });
    } else if (editedImageData.startsWith('data:image')) {
      // Decode Base64 image
      const parts = editedImageData.split(';base64,');
      const contentType = parts[0].split(':')[1];
      const base64Data = parts[1];
      attachments.push({
        filename: 'edited_image.png', // Or .jpg based on contentType
        content: Buffer.from(base64Data, 'base64'),
        contentType: contentType
      });
    }

    const mailOptions = {
      from: 'your_email@gmail.com',
      to: recipientEmail,
      subject: emailSubject,
      html: `<p>Here is your edited image:</p><img src="cid:edited_image" alt="Edited Image">`,
      attachments: [
        {
          filename: attachments[0].filename,
          content: attachments[0].content,
          contentType: attachments[0].contentType,
          cid: 'edited_image' // Content ID for embedding in HTML
        }
      ]
    };

    await transporter.sendMail(mailOptions);
    res.send('Email sent successfully!');
  } catch (error) {
    console.error('Error sending email:', error);
    res.status(500).send('Failed to send email.');
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Example Node.js server-side code to receive image data and send an email with the image attached.