Adding Blurhash to image uploads

Hello everyone.

To configure blur hash for v4 you can do as follows:

  1. By the using the register function in ./src/index.js do an extension the content type and redefine the default function ‘uploadFileAndPersist’ with blur hash logic.
    Add the following:
register({ strapi }) {

    strapi.contentType('plugin::upload.file').attributes.blurHash = {
      type: 'string',
    }

    strapi.plugin('upload').services.upload.uploadFileAndPersist = async function (fileData, { user } = {}) {

      const config = strapi.config.get('plugin.upload');

      const { getDimensions, generateThumbnail, generateResponsiveFormats } = strapi.plugin('upload').service('image-manipulation')

      await strapi.plugin('upload').provider.upload(fileData);

      const thumbnailFile = await generateThumbnail(fileData);

      if (thumbnailFile) {
        await strapi.plugin('upload').provider.upload(thumbnailFile);
        // Begin Override

        const encodeImageToBlurhash = (imageBuffer) =>
          new Promise((resolve, reject) => {
            sharp(imageBuffer)
              .raw()
              .ensureAlpha()
              .toBuffer((err, buffer, { width, height }) => {
                if (err) return reject(err);
                resolve(
                  encode(new Uint8ClampedArray(buffer), width, height, 4, 4)
                )
              });
          });

        const blurHash = await encodeImageToBlurhash(thumbnailFile.buffer);

        // Add a custom field to add a blurHash

        fileData.blurHash = blurHash;

        // End Override
        delete thumbnailFile.buffer;
        _.set(fileData, 'formats.thumbnail', thumbnailFile);
      }

      const formats = await generateResponsiveFormats(fileData);

      if (Array.isArray(formats) && formats.length > 0) {

        for (const format of formats) {

          if (!format) continue;

          const { key, file } = format;

          await strapi.plugin('upload').provider.upload(file);

          delete file.buffer;

          _.set(fileData, ['formats', key], file);

        }
      }
      const { width, height } = await getDimensions(fileData.buffer);

      delete fileData.buffer;

      _.assign(fileData, {
        provider: config.provider,
        width,
        height,
      });

      return this.add(fileData, { user });
    }
  },
  1. Additionally, you will need to define the functions used:
  const _ = require('lodash');
  const sharp = require('sharp')
  const { encode } = require('blurhash')

It is should work.