Cloudinary Blog

Build a Vue File Upload App for a Simplified Watermarking Process

By Christian Nwamba
Build a Vue File Upload App for a Simplified Watermarking Process

Update Cloudinary now has a new Vue SDK.

If you intend to build a photo gallery online, you have to seriously consider how to protect the images from users who are not buying them. While visitors need to see the picture before purchasing, there needs to be a way to ensure that even serious buyers are not tempted to use the images without agreeing to your license terms.

One way to address this issue is to overlay bold transparent text or an image - called a watermark - on the image. By doing so, the image can not be used unless the user pays for the rights to use it. Adding watermarks is not a simple task. You could hire resources for manually watermarking using a photo editor . But, this process is not scalable for a massive photo gallery. Automating the process to add default watermarks to every image can make the process more efficient.

Cloudinary, an end-to-end media solution enables you to simplify the watermarking process. Cloudinary offers storage, manipulation and delivery of your images and videos as a service. Dynamic transformations enable you to manipulate media files either on upload or by adjusting the delivery URLs,. One of the transformations-- overlay -- can be used to watermark images.

To see this in action, let’s build a Vue application to file upload to Cloudinary and creating a new watermarked version .

Note: Vue.js is an open-source JavaScript framework for building user interfaces and single-page applications.

Create a Cloudinary Account

We can start start with creating an account on Cloudinary and retrieving our cloud credentials before building the app. Sign up on Cloudinary for a free account:

Create a Cloudinary Account

When you sign up successfully, you're presented with a dashboard that holds your cloud credentials. You can safely store them for future use:

Dashboard

Provision a Server

Before diving into the Vue app, we need to provision the server/API, which the Vue application depends on to upload images. A simple Node server will do; thankfully, Cloudinary has a Node SDK to make our lives much easier.

Setup a new Node Project with npm:

Copy to clipboard
npm init

Install the following dependencies:

  • Express: HTTP routing library for Node
  • Body Parser: Attaches the request body on Express's req object, hence req.body
  • Connect Multiparty: Parse http requests with content-type multipart/form-data, also known as Vue file uploads.
  • Cloudinary: Node SDK for Cloudinary
  • CORS: To enable CORS
Copy to clipboard
npm install express body-parser connect-multiparty cors cloudinary --save

Create an index.js file at the root of the project folder. This is the only file this project will have (except for the package.json and dependencies). Import the installed dependencies in this file:

Copy to clipboard
const Express = require('express');
const multipart = require('connect-multiparty');
const bodyParser = require('body-parser')
const cloudinary = require('cloudinary');
const cors = require('cors');

Next, configure the body-parser and cors global middlewares:

Copy to clipboard
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

Configure Cloudinary with the credentials you retrieved from your dashboard after you created your account:

Copy to clipboard
cloudinary.config({
    cloud_name: 'CLOUD_NAME',
    api_key: 'API_KEY',
    api_secret: 'SECRET'
});

Add a POST route to handle incoming requests:

Copy to clipboard
// Multiparty middleware
const multipartMiddleware = multipart();

const app = Express();

app.post('/upload', multipartMiddleware, function(req, res) {
  // Upload files to cloudinary
  cloudinary.v2.uploader.upload(
    // File to upload
    req.files.image.path,
    // Overlay Tranformation
    { width: 700, overlay: `text:Times_90_bold:${encodeURIComponent(req.body.watermark)}`, gravity: "south", y: 80, color: "#FFFF0080" },
    // Callback function
    function(error, result) {
      res.json({data: result})
  })
});

Above is a POST route pointing to /upload. The route is configured with the multiparty middleware to parse uploaded files and attach to the req object.

When this route is hit, we attempt to upload the image using Cloudinary's upload() method. It takes a file path, optional transformation argument and a callback function to be executed when the upload is successful.

The transformations provided are:

  • Width: The width that the image should be scaled to
  • Overlay: Content that should be placed on the image. In our case a Times font, 90px font size, bold text. This text is gotten from the request payload via req.body
  • Gravity + y: Where the text should be placed. In this case, 80px from bottom
  • Color + Opacity: Color of the text. #FFFF00 is the color, while 80 attached at the end is the opacity value in percentage.

You can start listening to port:

Copy to clipboard
app.listen(process.env.PORT || 5000, () => console.log('Running...'))

Run the following command to start the server while we head right to building the client:

Copy to clipboard
node index.js

Vue File Upload Client

Our front-end app will be built using Vue (a progressive JavaScript framework). To get started, install the Vue CLI tool:

Copy to clipboard
npm install -g vue-cli

Next, create a simple Vue project using the Vue CLI tool we installed:

Copy to clipboard
vue init simple watermark-app

The index.html file found in the scaffold is enough for us to actualize our idea. Let's start by adding a basic template for a form that contains the upload and watermark text fields:

Copy to clipboard
<h2 class="text-center">Watermarker</h2>
<form enctype="multipart/form-data" @submit.prevent="onSubmit">
  <div class="form-group">
    <label for="">Watermark Text:</label>
    <input type="text" class="form-control" name="text" v-model="model.text">
  </div>
  <div class="form-group">
    <label for="">File:</label>
    <input type="file" class="form-control" accept="image/*" name="image" v-on:change="upload($event.target.files)">
  </div>
  <div class="form-group">
    <button class="btn btn-primary">Upload</button>
  </div>
</form>

 <div class="col-md-6">
   <img:src="watermarked" class="img-responsive" alt="">
 </div>

The text is bound to a model, while the upload field is bound to an upload event handler. When the "Upload" button is clicked, the onSubmit method on our Vue instance will be called.

There is also an image at the bottom of the template that its src attribute is bound to watermarked. This will be where the watermarked images will be placed.

This is the model on our Vue instance:

Copy to clipboard
data: function() {
   return {
     model: {
       text: '',
       image: null
     },
     watermarked: null
   }
 },

Because we cannot have a two-way binding on an upload field, we attach a change event. before and after properties will be updated with the URL of non-watermarked and watermarked images. When the field changes, the upload method is called, which should set the value of model.image:

Copy to clipboard
methods: {
   upload: function(files) {
     this.model.image = files[0]
   }
 }

Finally, when the form is submitted, we assemble the uploaded file, as well as the watermark text, using FormData:

Copy to clipboard
methods: {
  onSubmit: function() {
    // Assemble for data
    const formData = new FormData()
    formData.append('image', this.model.image);
    formData.append('watermark', this.model.text);
    // Post to server
    axios.post('http://localhost:5000/upload', formData)
    .then(res => {
      // Update UI
      this.watermarked = res.data.data.url
    })
  },
  // ...
 }

You can launch the app and try to upload an image. You should get the following response:

Watermarker

Custom Font

Cloudinary enables you to use custom fonts. This comes handy when universally supported fonts do not suit your brand guidelines, and a custom font is required. Before using a custom font, you need to upload it with your chosen public ID:

Copy to clipboard
cloudinary.v2.uploader.upload("fonts/AlexBrush-Regular.ttf", 
    {resource_type: 'raw', 
    type: 'authenticated', 
    public_id: 'AlexBrush-Regular.ttf'}, callbackFunction)

Then you can use it as the font for the text overlay, while uploading an image to your Cloudinary server:

Copy to clipboard
app.post('/upload', multipartMiddleware, function(req, res) {
  // Upload files to cloudinary
  cloudinary.v2.uploader.upload(
    // File to upload
    req.files.image.path,
    // Overlay Tranformation
    { width: 700, overlay: `text:AlexBrush-Regular.ttf_90_bold:${encodeURIComponent(req.body.watermark)}`, gravity: "south", y: 80, color: "#FFFF0080" },
    // Callback function
    function(error, result) {
      res.json({data: result})
  })
});

Note that the overlay transformation property has changed from text:Times_90_bold... to text:AlexBrush-Regular.ttf_90_bold....

To always get the expected behavior from custom fonts, it's important to follow these guidelines:

  • .ttf and .otf font types are supported.
  • Make sure to include the file extension when referencing the public_id of the raw file.
  • To make use of bold or italic font styles, upload separate font files for each emphasis style and specify the relevant file in the overlay transformation.
  • A custom font is available only to the specific account or sub-account where it was uploaded.
  • Underscores are not supported in custom font names. When uploading the font as a raw file, make sure the public_id does not include an underscore.
  • As with any resource you upload to Cloudinary, it is your responsibility to make sure you have the necessary license and redistribution rights for any custom fonts you use.

Conclusion

There are various techniques you could use for adding your brand logo or custom text as watermarks. Cloudinary makes it easy to implement, automate and scale your watermarking requirements. Learn more overlay docs about different styling techniques and take it for a spin (for free).

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more