Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize images for different responsive views?

I created a site with nuxt.js and bootstrap. For the responsive views i need to create different image sizes. Nuxt.js can't resize images. How do you do this?

like image 937
poldixd Avatar asked Dec 11 '22 08:12

poldixd


2 Answers

Now I have the solution. Install responsive-loader and sharp.

Modify the nuxt.config.js and add the code under build: {}:

build: {
  /*
  ** Run ESLint on save
  */
  extend (config, { isDev, isClient }) {

    // Default block
    if (isDev && isClient) {
      config.module.rules.push({
        enforce: 'pre',
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        exclude: /(node_modules)/
      })
    }
    // Default block end


    // here I tell webpack not to include jpgs and pngs
    // as base64 as an inline image
    config.module.rules.find(
      rule => rule.loader === "url-loader"
    ).exclude = /\.(jpe?g|png)$/;

    // now i configure the responsive-loader
    config.module.rules.push({
        test: /\.(jpe?g|png)$/i,
        loader: 'responsive-loader',
        options: {
            min: 575,
            max: 1140,
            steps: 7,
            placeholder: false,
            quality: 60,
            adapter: require("responsive-loader/sharp")
        }
    })

  }
}

Now you can use the following code to display images

<img :src="require('~/assets/images/Foo.jpg?size=400')" :srcset="require('~/assets/images/Foo.jpg').srcSet">
like image 140
poldixd Avatar answered May 16 '23 08:05

poldixd


If you don't want to rely on webpack for responsively loading images, you may want to try this nuxt module: https://github.com/reallifedigital/nuxt-image-loader-module

The downside to this module is that it doesn't currently support srcset natively and requires a local installation of the Graphicsmagick library. The upside is that anything that's available in Graphicsmagick (image manipulation wise) can be used to process your images. Also, you can implement your own image srcset from following the instructions and implementing your image tag like this:

<img src="image.png" srcset="image-1x.png?style=1x 1x, image-2x.png?style=2x 2x alt="" />

You should be able to implement any responsive image this way.

For our responsive views in nuxt, such as a 'feed' of latest content, we wanted to use smaller images from what was being used on the main articles, so this module does exactly what we need it to.

Disclosure: I wrote this module to solve our particular responsive requirement which, given the original poster's description, sounds like there's a lot of overlap.

like image 34
Barry Fisher Avatar answered May 16 '23 06:05

Barry Fisher