<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Image Resizing Archives &#8211; Wadiweb</title>
	<atom:link href="https://www.wadiweb.com/tag/image-resizing/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description></description>
	<lastBuildDate>Sat, 01 Oct 2022 13:59:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.5</generator>
	<item>
		<title>How to Resize Images for Your Website</title>
		<link>https://www.wadiweb.com/how-to-resize-images-for-your-website/</link>
		
		<dc:creator><![CDATA[Mohammed Rezq]]></dc:creator>
		<pubDate>Sat, 01 Oct 2022 13:54:37 +0000</pubDate>
				<category><![CDATA[Website Optimization]]></category>
		<category><![CDATA[Image Optimization]]></category>
		<category><![CDATA[Image Resizing]]></category>
		<category><![CDATA[Page speed loading]]></category>
		<guid isPermaLink="false">https://www.wadiweb.com/?p=3785</guid>

					<description><![CDATA[<p>Websites nowadays contains hundreds if not thousands of images, so resizing images in bulk for your website is essential. Many online services and WordPress plugins provide such service, but it might be limiting to some extent. Using JavaScript you can achieve a very good results with minimal effort and almost for free!. We will be...</p>
<p>The post <a href="https://www.wadiweb.com/how-to-resize-images-for-your-website/">How to Resize Images for Your Website</a> appeared first on <a href="https://www.wadiweb.com">Wadiweb</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Websites nowadays contains hundreds if not thousands of images, so resizing images in bulk for your website is essential. Many online services and WordPress plugins provide such service, but it might be limiting to some extent. Using JavaScript you can achieve a very good results with minimal effort and almost for free!.</p>



<p>We will be using Sharp Js Library which is an great library for optimizing, resizing , It also has many other features that will help you to improve your images with ease. In this article, we will focus on resizing images using Sharp.</p>



<p><strong>Sharp </strong>requires Node.js to be installed on your Operating System, which you can download below. ( I recommend downloading and installing the stable version for your operating system ).</p>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button alignleft has-custom-font-size is-style-fill" style="font-size:16px"><a class="wp-block-button__link" href="https://nodejs.org/en/download/" target="_blank" rel="noreferrer noopener">Download Node</a></div>
</div>



<p></p>



<p><strong>Sharp</strong> is a high-speed Node.js module to convert large images in standard formats to smaller, web-friendly JPEG, PNG, WebP, GIF, and AVIF images of varying dimensions.</p>



<p>Using <strong>Sharp</strong> to resize your images is very easy to do, and we will go through the steps to resize your images in bulk for your website.</p>



<h2 class="wp-block-heading">1- Install Sharp Library</h2>



<p>The first step is installing Sharp using npm or yarn</p>



<p>Open your command line terminal in this folder, -I use&nbsp;<a href="https://git-scm.com/downloads" target="_blank" rel="noreferrer noopener">Gitbash</a>– then run the following command</p>



<h4 class="wp-block-heading">NPM</h4>



<p>If you have npm installed then run this line.</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-lang="Bash"><code>npm i sharp</code></pre></div>



<h4 class="wp-block-heading">Yarn</h4>



<p>Or you can replace npm install with yarn add if you have yarn in your system.</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-lang="Bash"><code>yarn add sharp</code></pre></div>



<p>It should install the required packages within moments.</p>



<h2 class="wp-block-heading">Script</h2>



<p>Now we should create a new file that will contain our code to resize images, Create a file name <strong>index.js</strong> and add the following code.</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-js" data-lang="JavaScript"><code>const sharp = require(&quot;sharp&quot;);
const fs = require(&quot;fs&quot;);
const path = require(&quot;path&quot;);</code></pre></div>



<p>The packages are Sharp Library(sharp) which we just installed earlier, Filesystem (fs), and path (path) packages which should already.</p>



<p>Now let&#8217;s create a folder that will contain our original images we will name (images). and another folder for outputting resized images we will name (output). </p>



<p>The packages and folders should look something like this</p>



<h4 class="wp-block-heading">Images Resizing Structure</h4>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="355" src="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01134851/sharp-optimizing-1024x355.webp" alt="" class="wp-image-4133" srcset="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01134851/sharp-optimizing-1024x355.webp 1024w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01134851/sharp-optimizing-300x104.webp 300w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01134851/sharp-optimizing-768x266.webp 768w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01134851/sharp-optimizing.webp 1228w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>You can clone the structure and the code from the <a href="https://github.com/mohammedrezq/sharp-optimizing-images" target="_blank" rel="noreferrer noopener nofollow">GitHub repo Sharp Images Optimization</a></p>



<p>We will add the original images that we will <strong>resize</strong> to the (<strong>images</strong>) folder.</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-js" data-lang="JavaScript"><code>const directoryName = &quot;images&quot;;

const fileNames = fs.readdirSync(directoryName);</code></pre></div>



<p>directoryName variable is the images folder name, and filesNames variable we get to loop through for resizing using Sharp.</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-js" data-lang="JavaScript"><code>
fileNames.forEach((file) =&gt; {

  const fileFormat = getExtension(file);
  let sh = sharp(&quot;./images/&quot; + file);

  if( &#39;jpg&#39; == fileFormat ) {
    sh.jpeg({
      quality: 80,
      progressive: true,
    }).resize(
      {
        fit:  sharp.fit.contain,
        width: 900,
      }
    )
  } 
});

function getExtension(filename) {
  let ext = path.extname(filename || &quot;&quot;).split(&quot;.&quot;);

  return ext[ext.length - 1];
}</code></pre></div>



<p>Now we will loop through all images that are jpg formatted, and set those images&#8217; quality to 80 (percent) you can set the number higher or lower. you can read more about available options for image optimization (<a href="https://sharp.pixelplumbing.com/api-output">Output Images</a>).</p>



<p>Resizing Images use the method resize, and we will keep images same dimensions, width is set to 900 (PX), this will make the images&#8217; width to 900 Pixels and the height will be resized accordingly with the same dimensions.</p>



<p>You can check more options from (<a href="https://sharp.pixelplumbing.com/api-resize" target="_blank" rel="noreferrer noopener nofollow">Resizing Images</a>) Options.</p>



<p>Add similar logic for WebP and PNG formatted images</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-js" data-lang="JavaScript"><code>fileNames.forEach((file) =&gt; {

  const fileFormat = getExtension(file);
  let sh = sharp(&quot;./images/&quot; + file);

  if( &#39;jpg&#39; == fileFormat ) {
    sh.jpeg({
      quality: 80,
      progressive: true,
    }).resize(
      {
        fit:  sharp.fit.contain,
        width: 900,
      }
    )
  } else if (&#39;png&#39; === fileFormat) {
    sh.png({
      quality: 80,
      progressive: true,
    }).resize(
      {
        fit:  sharp.fit.contain,
        width: 900,
      }
    )
  } else if(&#39;webp&#39; === fileFormat){
    sh.webp({lossless:true, quality: 80, alphaQuality: 100, force: true}).resize(
        {fit: sharp.fit.contain, width: 900}
      )
  }
});

function getExtension(filename) {
  let ext = path.extname(filename || &quot;&quot;).split(&quot;.&quot;);

  return ext[ext.length - 1];
}</code></pre></div>



<p>The final code in index.js file should be</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-js" data-lang="JavaScript"><code>// Packages
const sharp = require(&quot;sharp&quot;);
const fs = require(&quot;fs&quot;);
const path = require(&quot;path&quot;);

// Original Images directory
const directoryName = &quot;images&quot;;

// Get file names
const fileNames = fs.readdirSync(directoryName);

// Loop through images
fileNames.forEach((file) =&gt; {

  // Get image format (extension)
  const fileFormat = getExtension(file);

  console.log(&quot;fileFormat&quot;, fileFormat)
  if (fileFormat === &quot;svg&quot;) {
    console.log(&quot;SVGs are not processed in this script at the moment&quot;);
    return;
  }
  let sh = sharp(&quot;./images/&quot; + file);

  if( &#39;jpg&#39; == fileFormat ) {
    sh.jpeg({
      quality: 80,
      progressive: true,
    }).resize(
      {
        fit:  sharp.fit.contain,
        width: 900,
      }
    )
  } else if (&#39;png&#39; === fileFormat) {
    sh.png({
      quality: 80,
      progressive: true,
    }).resize(
      {
        fit:  sharp.fit.contain,
        width: 900,
      }
    )
  } else if(&#39;webp&#39; === fileFormat){
    sh.webp({lossless:true, quality: 80, alphaQuality: 100, force: true}).resize(
        {fit: sharp.fit.contain, width: 900}
      )
  }


  console.log(&#39;output/&#39; + file);
  let fileNameWOExtension = file.replace(/\.[^/.]+$/, &quot;&quot;);

  console.log(fileNameWOExtension);


  sh.toFile(&#39;output/&#39; + `${file}`, function (err, info) {
    // console.log(info);
    if(err) {
      console.log(err + &quot;Error occurred while optimization process&quot;)
    }
  })
});

// Get Image Extension
function getExtension(filename) {
  let ext = path.extname(filename || &quot;&quot;).split(&quot;.&quot;);

  return ext[ext.length - 1];
}
</code></pre></div>



<p>After finishing the code and organizing our folders Let&#8217;s add our images and test resizing images</p>



<p>In images folder we have about 25 images free from <a href="https://www.pexels.com/">pexels</a>, images varying in size so we will use Sharp to resize those images making their width 900 Pixels and the height will resize to the same aspect ratio.</p>



<p>Run the following command in the Visual Studio Code terminal (or Git bash or any other terminal to run your commands).</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="576" src="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132252/node-index.-resizing-images-1024x576.webp" alt="" class="wp-image-4121" srcset="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132252/node-index.-resizing-images-1024x576.webp 1024w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132252/node-index.-resizing-images-300x169.webp 300w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132252/node-index.-resizing-images-768x432.webp 768w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132252/node-index.-resizing-images-1536x864.webp 1536w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132252/node-index.-resizing-images.webp 1919w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-lang="Bash"><code>node index.js</code></pre></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="576" src="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132301/resized-images-1024x576.webp" alt="" class="wp-image-4124" srcset="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132301/resized-images-1024x576.webp 1024w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132301/resized-images-300x169.webp 300w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132301/resized-images-768x432.webp 768w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132301/resized-images-1536x864.webp 1536w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01132301/resized-images.webp 1919w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>You should see the console logs appear in the terminal while resizing images. The time of resizing images depends on the size and quantity of the images. So 25 images didn&#8217;t take more than 2 seconds.</p>



<p>So, let&#8217;s see images before and after resizing dimensions</p>



<h4 class="wp-block-heading">Before Resizing</h4>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="692" height="1024" src="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-692x1024.jpg" alt="" class="wp-image-4142" srcset="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-692x1024.jpg 692w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-203x300.jpg 203w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-768x1137.jpg 768w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-1037x1536.jpg 1037w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-1383x2048.jpg 1383w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135905/before-scaled.jpg 1729w" sizes="(max-width: 692px) 100vw, 692px" /></figure>



<h4 class="wp-block-heading">After Resizing</h4>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="691" height="1024" src="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135853/after-691x1024.jpg" alt="" class="wp-image-4141" srcset="https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135853/after-691x1024.jpg 691w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135853/after-203x300.jpg 203w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135853/after-768x1137.jpg 768w, https://cdn.wadiweb.com/wp-content/uploads/2022/10/01135853/after.jpg 900w" sizes="(max-width: 691px) 100vw, 691px" /></figure>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Resizing images using Sharp doesn&#8217;t require much work after the initial setup. you can resize your images very fast and with many custom options available.</p>



<p>Learn how to optimize images for your website to be production ready (<a href="https://www.wadiweb.com/how-to-optimizie-images-for-your-website/">How to Optimize Images for Your Website</a>).</p>
<p>The post <a href="https://www.wadiweb.com/how-to-resize-images-for-your-website/">How to Resize Images for Your Website</a> appeared first on <a href="https://www.wadiweb.com">Wadiweb</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
