Code Monkey home page Code Monkey logo

strapi-blurhash's Introduction

Strapi plugin strapi-blurhash

A plugin for Strapi CMS that generates blurhash for your uploaded images

Installation

To install, run:

npm install strapi-blurhash

Open/create file config/plugins.js. Enable this plugin by adding:

module.exports = {
    ...
    'strapi-blurhash': {
      enabled: true,
      config: {
        regenerateOnUpdate: true,
        forceRegenerateOnUpdate: false,
      }
    },
  }

How to generate blurhash for an image

In the Strapi Dashboard open Content Manager. Edit one collection/single type. Add or edit a Media field type and save the collection/single type.

How to get blurhash

Target a Strapi REST API endpoint. For example:

localhost:1337/api/products?populate=Image.*

The response will be a JSON containing blurhash along with rest of the image data:

{
  "data": [
    {
      "id": 6,
      "attributes": {
        "name": "Test",
        "createdAt": "2022-10-27T14:52:04.393Z",
        "updatedAt": "2022-10-28T09:58:22.238Z",
        "Image": {
          "data": {
            "id": 80,
            "attributes": {
              "name": "image.png",
              "alternativeText": "image.png",
              "caption": "image.png",
              "width": 960,
              "height": 168,
              "formats": {
                ...
              },
              "hash": "image_ed1fbcdba0",
              "ext": ".png",
              "mime": "image/png",
              "size": 4.63,
              "url": "/uploads/image_ed1fbcdba0.png",
              "previewUrl": null,
              "provider": "local",
              "provider_metadata": null,
              "createdAt": "2022-10-28T09:42:02.471Z",
              "updatedAt": "2022-10-28T09:42:02.471Z",
              "blurhash": "U{Nd,T?bof?u_Nxuj[x[objZayoe_Mxuj[x["
            }
          }
        }
      }
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "pageSize": 25,
      "pageCount": 1,
      "total": 1
    }
  }
}

Regenerating Existing Content

If you've recently installed this plugin and already have existing media content, you can easily update the blurhash for these items. Use the Regenerator plugin to efficiently handle this task:

This additional plugin can automate the process.

Changelog

All notable changes to this project will be documented in this section.

[1.2.1]

Changed

  • now using sharp instead of canvas due to issues with .webp images.

[1.2.2]

Added

  • forceRegenerateOnUpdate configuration option to force the regeneration of blurhash on every update, regardless of the existing blurhash.

[1.2.3]

Fixed

  • fixed a bug with the image url

[1.2.4]

Fixed

  • fixed a bug with the image url var

[1.2.5]

Changed

  • updated the readme file

strapi-blurhash's People

Contributors

emil-petras avatar trijpstra-fourlights avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

strapi-blurhash's Issues

Does not generate hash when updating file

Hi! Thanks for the package, works like a charm when uploading new images!

I noticed however that when, say, updating the title of an image, the hash would not get updated. this is because the beforeUpdateData looks like this.

{
  name: 'Marcel.jfif',
  alternativeText: "Marcel's face",
  caption: '',
  folder: undefined,
  folderPath: undefined,
  updatedBy: 3,
  updatedAt: 2023-01-26T12:45:07.219Z
}

I get that that may be the indented behavior, but I wanted a way to easily generate hashes for existing images without having to reupload everything.

For anyone like me, replace the code in bootstrap.js with the following and run patch-package for that result. If the image is newly created/uploaded, it will work as usual. If not, it will get the full data from the db, check if there already is a hash for it, and if not generate one.

'use strict';

module.exports = ({ strapi }) => {

  const generateBlurhash = async (event) => {
    const { data, where } = event.params;

    if ((data.mime && data.mime.startsWith('image/'))) {
      data.blurhash = await strapi.plugin('strapi-blurhash').service('blurhash').generateBlurhash(data.url);
    }

    const fullData = await strapi.db.query('plugin::upload.file').findOne({
      select: ['url', 'blurhash', 'name', 'mime'],
      where
    })

    if ((fullData.mime && fullData.mime.startsWith('image/')) && !fullData.blurhash) {
      data.blurhash = await strapi.plugin('strapi-blurhash').service('blurhash').generateBlurhash(fullData.url);
    }
  };

  strapi.db.lifecycles.subscribe({
    models: ['plugin::upload.file'],
    beforeCreate: generateBlurhash,
    beforeUpdate: generateBlurhash,
  });
};

Issue with plugin version deployed on NPM

The latest version published on npm is 1.3.0 that's missing from github and also has an error
Error: Could not load js config file \node_modules\strapi-blurhash\strapi-server.js: Cannot find module 'canvas'

Issue with Image Uploads and White Screen on Strapi Versions 4.13.2 and Above

Issue Summary:
On versions of Strapi 4.13.2 and up, attempting to upload new images to the media library leads to a white screen, rendering no images correctly. This issue is accompanied by a console error message: Failed to construct 'URL': Invalid URL. My Strapi application is connected to a Postgres database.

Steps to reproduce:
Upgrade Strapi to version 4.13.2 or a later version.
Attempt to upload a new image to the media library.

Expected Behavior:
The image should be uploaded to the media library without any issues, and it should be rendered correctly on the screen.

Possible Solutions/Workarounds Tried:
I've attempted to find a solution but haven't been successful so far. Downgrading the application to version 4.13.1 and creating a new database is a workaround, but it's not an ideal solution.

Screenshot of error

Error: Cannot read properties of null (reading 'mime'). where from event.params.data is undefined

Strapi & Strapi Blurhash details:

"dependencies": {
    // ...
    "@strapi/strapi": "4.9.0",
    "strapi-blurhash": "^1.1.0",
    // ...
  }

I am unable to use the plugin and every upload throws an error. seems like event.params.where is undefined. Maybe something changed in strapi which needs to be handled differently.

// event.params.data
{
  name: '1440 - [email protected]',
  alternativeText: undefined,
  caption: undefined,
  folder: null,
  folderPath: '/',
  hash: '1440_02_2x_600588b2dc',
  ext: '.png',
  mime: 'image/png',
  size: 51.66,
  tmpWorkingDirectory: '/zb/dm5vv8357gz20k6h0wkl29k80000gn/T/strapi-upload-v5RrQH',
  getStream: [Function (anonymous)],
  width: 2880,
  height: 2048,
  url: '/uploads/1440_02_2x_600588b2dc.png',
  formats: {
    thumbnail: {
      name: 'thumbnail_1440 - [email protected]',
      hash: 'thumbnail_1440_02_2x_600588b2dc',
      ext: '.png',
      mime: 'image/png',
      path: null,
      getStream: [Function: getStream],
      width: 219,
      height: 156,
      size: 10.73,
      url: '/uploads/thumbnail_1440_02_2x_600588b2dc.png'
    },
    medium: {
      name: 'medium_1440 - [email protected]',
      hash: 'medium_1440_02_2x_600588b2dc',
      ext: '.png',
      mime: 'image/png',
      path: null,
      getStream: [Function: getStream],
      width: 768,
      height: 546,
      size: 52.8,
      url: '/uploads/medium_1440_02_2x_600588b2dc.png'
    },
    small: {
      name: 'small_1440 - [email protected]',
      hash: 'small_1440_02_2x_600588b2dc',
      ext: '.png',
      mime: 'image/png',
      path: null,
      getStream: [Function: getStream],
      width: 576,
      height: 410,
      size: 36.44,
      url: '/uploads/small_1440_02_2x_600588b2dc.png'
    },
    large: {
      name: 'large_1440 - [email protected]',
      hash: 'large_1440_02_2x_600588b2dc',
      ext: '.png',
      mime: 'image/png',
      path: null,
      getStream: [Function: getStream],
      width: 992,
      height: 705,
      size: 74.35,
      url: '/uploads/large_1440_02_2x_600588b2dc.png'
    },
  },
  provider: 'local',
  updatedBy: 1,
  createdBy: 1,
  createdAt: 2023-03-31T09:23:47.249Z,
  updatedAt: 2023-03-31T09:23:47.249Z
}
// event.params.where
undefined

// fullData
fullData::  null

error: Cannot read properties of null (reading 'mime')
TypeError: Cannot read properties of null (reading 'mime')
    at Object.generateBlurhash (<path>/node_modules/strapi-blurhash/server/bootstrap.js:20:21)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.run (<path>/node_modules/@strapi/database/lib/lifecycles/index.js:76:11)
    at async Object.create (<path>/node_modules/@strapi/database/lib/entity-manager/index.js:213:22)
    at async Object.add (<path>/node_modules/@strapi/plugin-upload/server/services/upload.js:364:17)
    at async Promise.all (index 0)
    at async Object.upload (<path>/node_modules/@strapi/plugin-upload/server/services/upload.js:172:23)
    at async uploadFiles (<path>/node_modules/@strapi/plugin-upload/server/controllers/admin-upload.js:79:27)
    at async Object.upload (<path>/node_modules/@strapi/plugin-upload/server/controllers/admin-upload.js:101:5)
    at async returnBodyMiddleware (<path>/node_modules/@strapi/strapi/lib/services/server/compose-endpoint.js:52:18

Thank you in advance for looking into it :)

Could not load the "sharp" module

Hello,
I have this error in local (MacOS) and in production (Debian) :

[2024-05-23 18:13:47.266] debug: ⛔️ Server wasn't able to start properly.
[2024-05-23 18:13:47.267] error: Could not load js config file /app/node_modules/strapi-blurhash/strapi-server.js: Could not load the "sharp" module using the linux-x64 runtime

I think there is an issue in the way that the plugin uses sharp.

Thank you for your help.

Could not load the "sharp" module using the win32-x64 runtime ERR_DLOPEN_FAILED: The specified procedure could not be found.

Error: Could not load js config file C:\laragon\www\cafs\node_modules\strapi-blurhash\strapi-server.js: Could not load the "sharp" module using the win32-x64 runtime
ERR_DLOPEN_FAILED: The specified procedure could not be found.
\?\C:\laragon\www\cafs\node_modules@img\sharp-win32-x64\lib\sharp-win32-x64.node
Possible solutions:

  • Ensure optional dependencies can be installed:
    npm install --include=optional sharp
    yarn add sharp --ignore-engines
  • Ensure your package manager supports multi-platform installation:
    See https://sharp.pixelplumbing.com/install#cross-platform
  • Add platform-specific dependencies:
    npm install --os=win32 --cpu=x64 sharp
  • Using the canvas package on Windows?
    See https://sharp.pixelplumbing.com/install#canvas-and-windows
  • Check for outdated versions of sharp in the dependency tree:
    npm ls sharp
  • Consult the installation documentation:
    See https://sharp.pixelplumbing.com/install
    at loadJsFile (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\core\app-configuration\load-config-file.js:18:11)
    at loadFile (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\core\app-configuration\load-config-file.js:35:14)
    at Object.loadPlugins (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\core\loaders\plugins\index.js:103:26)
    at async Strapi.loadPlugins (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\Strapi.js:352:5)
    at async Promise.all (index 3)
    at async Strapi.register (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\Strapi.js:392:5)
    at async Strapi.load (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\Strapi.js:503:5)
    at async workerProcess (C:\laragon\www\cafs\node_modules@strapi\strapi\lib\commands\actions\develop\action.js:110:26)

Error parsing URL with AWS upload provider

I think an update to the strapi upload plugin has broken something here. When I try to upload an image I get this error:

I'm also uploading an SVG which obviously won't work but it used to just get ignored.

[2024-04-25 13:46:32.381] http: GET /upload/folders?page=1&sort=createdAt:DESC&pageSize=50&filters[$and][0][parent][id][$null]=true&pagination[pageSize]=-1 (269 ms) 200
[2024-04-25 13:46:38.198] error: Error generating blurhash: Failed to parse URL from http://localhost:1337https://[bucketname].s3.eu-north-1.amazonaws.com/dgk_48510e3136.svg
[2024-04-25 13:46:38.200] error: Failed to parse URL from http://localhost:1337https://[bucketname].s3.eu-north-1.amazonaws.com/dgk_48510e3136.svg
TypeError: Failed to parse URL from http://localhost:1337https://[bucketname].eu-north-1.amazonaws.com/dgk_48510e3136.svg
    at node:internal/deps/undici/undici:12618:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.generateBlurhash (/Users/samhenderson/Development/[projectname]/node_modules/strapi-blurhash/server/services/blurhash.js:7:24)
    at async generateBlurhash (/Users/samhenderson/Development/[projectname]/node_modules/strapi-blurhash/server/bootstrap.js:11:23)
    at async Object.run (/Users/samhenderson/Development/[projectname]/node_modules/@strapi/database/dist/index.js:6029:11)
    at async Object.create (/Users/samhenderson/Development/[projectname]/node_modules/@strapi/database/dist/index.js:5092:22)
    at async Object.add (/Users/samhenderson/Development/[projectname]/node_modules/@strapi/plugin-upload/server/services/upload.js:407:17)
    at async Promise.all (index 0)
    at async Object.upload (/Users/samhenderson/Development/[projectname]/node_modules/@strapi/plugin-upload/server/services/upload.js:210:23)
    at async uploadFiles (/Users/samhenderson/Development/[projectname]/node_modules/@strapi/plugin-upload/server/controllers/admin-upload.js:79:27)

Bump nodejs to 20

error [email protected]: The engine "node" is incompatible with this module. Expected version ">=14.19.1 <=18.x.x". Got "20.9.0"
[2023-10-26 17:53:26] │ error Found incompatible module.

This is on the latest strapi.

Please remove the Node version check to make it easier for future updates

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.