aboutsummaryrefslogtreecommitdiff
path: root/public/create-placeholder-images-with-sharp.html
blob: 9a3db25e015a6c4e94faff4f756bd9b84a4aee55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!doctype html><html lang=en-us><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><link href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL69vf8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv76+/8LBwQkAAAAAAAAAAAAAAAC+vb3/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL+9vf/Bv78JAAAAAAAAAAAAAAAAu7q6/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7ubr/vr29CAAAAAAAAAAAy8nJAZ6foP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnqGj/6GipAoAAAAAHLjU/xcXHf/BwsL/I8XY/yPK3v8XGiD/IbjL/yPF2f8XGiD/Fxkf/yLF2f8gnK3/Fxog/62ztv8fwNf/FRcd/x271v8mz93/GRsi/xkXHf8p097/GiIp/xobIv8p0t3/KdPe/xocIv8fYmr/KNPe/xoZH/8aHCL/J87c/xy81/8VFxz/IsPZ/8zS0/8XGiD/Ir/R/yPH2/8XGiD/Fxkf/yPH2/8dd4T/GBog/yPJ3f8jyNr/uru9/xcUGv8cudb/EhITDKi5vRKlvMP/RUpOERwcHRAdOj4QHTk8EBwdHRAdNTgQHTo/EBwcHRAcHB0QSGduEKW4vf+koqQfHzg+EBqz0ewSFRv7EyMr/xq51vsTERb7ExUb+xq41fsau9j7ExUb+xiPp/sZudb7ExUb+xMVG/sZuNX/GKvI/BIUGfMdvdn/IrfL/xcaIP8n1eb/J9Dh/xkcIf8ZGR7/J8/f/xxCSv8ZGyH/J9Dg/ybQ4P8ZHCL/FSQs/yPK3/8UExj/GE1b/ybS5P8ZGB7/Ghwj/ynW5P8p2Ob/Ghwi/yWrtv8p1eH/Ghwi/xocIv8p1uT/J8XT/xkcIv8m1un/Hb7d/xUYH/8hzOr/HtHu/xcaIf8XGB//I8vi/xgxOv8XGSD/I8rg/yPK4P8XGiD/GUFL/yPP6f8SERj/Fhkh/x3A4f8AAAAAJ2f9/ydr//8mZPH/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlYu38J2v//ydo/f8AAAAAAAAAAAd8/fkFqf//Iob8sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMY39awWr//8FfP3/AAAAAAAAAAAFm/7/SfD//wR+/f8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOB/f9B7v//BaX+/wAAAAAAAAAAQ878SAyZ/v9n1v4KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADu9v8DDJb+/z3N/XgAAAAA3/sAAN/7AADf+wAA3/sAAAAAAAAAAAAAAAAAAN/7AAAAAAAAAAAAAAAAAAAAAAAAj/EAAI/5AACP8QAA3/sAAA==" rel=icon type=image/x-icon><title>Create placeholder images with sharp Node.js image processing library</title><meta name=description content="I have been searching for a solution to pre-generate some placeholder images forimage server I needed to develop that resizes images on S3."><link rel=alternate type=application/rss+xml title="Mitja Felicijan's posts" href=https://mitjafelicijan.com/index.xml><link rel=alternate type=application/rss+xml title="Mitja Felicijan's notes" href=https://mitjafelicijan.com/notes.xml><style>body{padding:1rem;max-width:760px;background:#fff;font-family:times new roman,Times,serif;line-height:1.35rem}hr{margin-block-start:1.5rem}h1,h2,h3{line-height:initial}footer{margin-block-start:3rem}table{max-width:100%;border-collapse:separate;border-spacing:2px;border:1px solid #000;border-left:1px solid #999;border-top:1px solid #999}blockquote{font-style:italic}table thead{background:#eee}td,th{border:1px solid #000;padding:4px;border-right:1px solid #999;border-bottom:1px solid #999;text-align:left}pre{text-wrap:nowrap;overflow-x:auto;margin-block-start:1.5rem;margin-block-end:1.5rem;padding:.5rem 0;border-top:1px solid #000;border-bottom:1px solid #000}pre code{line-height:1.3em}pre,code,pre *,code *{font-family:monospace;font-size:initial!important}img,video,audio{max-width:100%}header{display:flex;flex-direction:row;gap:3rem}nav{display:flex;gap:.75rem}.pstatus-orange{background:gold}.pstatus-green{background:#9acd32}.pstatus-red{background:#cd5c5c}@media only screen and (max-width:600px){header{flex-direction:column;gap:1rem}a{word-wrap:break-word}}</style><header><nav class=main><a href=/>Home</a>
<a href=https://git.mitjafelicijan.com/ target=_blank>Git</a>
<a href=https://files.mitjafelicijan.com/ target=_blank>Files</a>
<a href=/mitjafelicijan.pgp.pub.txt target=_blank>PGP</a>
<a href=/curriculum-vitae.html>CV</a>
<a href=/index.xml target=_blank>RSS</a></nav></header><main><div><h1>Create placeholder images with sharp Node.js image processing library</h1><p>Mar 27, 2020<div><p>I have been searching for a solution to pre-generate some placeholder images for
image server I needed to develop that resizes images on S3. I though this would
be a 15min job and quickly found out how very mistaken I was.<p>Even though Node.js is not really the best way to do this kind of things (surely
something written in C or Rust or even Golang would be the correct way to do
this but we didn't need the speed in our case) I found an excellent library
<a href=https://github.com/lovell/sharp>sharp - High performance Node.js image
processing</a>.<p>Getting things running was a breeze.<h2 id=fetch-image-from-s3-and-save-resized>Fetch image from S3 and save resized</h2><pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:#00f>const</span> sharp = require(<span style=color:#a31515>&#39;sharp&#39;</span>);
</span></span><span style=display:flex><span><span style=color:#00f>const</span> aws = require(<span style=color:#a31515>&#39;aws-sdk&#39;</span>);
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#00f>const</span> x,y = 100;
</span></span><span style=display:flex><span><span style=color:#00f>const</span> s3 = <span style=color:#00f>new</span> aws.S3({});
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>aws.config.update({
</span></span><span style=display:flex><span>  secretAccessKey: <span style=color:#a31515>&#39;secretAccessKey&#39;</span>,
</span></span><span style=display:flex><span>  accessKeyId: <span style=color:#a31515>&#39;accessKeyId&#39;</span>,
</span></span><span style=display:flex><span>  region: <span style=color:#a31515>&#39;region&#39;</span>
</span></span><span style=display:flex><span>});
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#00f>const</span> originalImage = <span style=color:#00f>await</span> s3.getObject({
</span></span><span style=display:flex><span>  Bucket: <span style=color:#a31515>&#39;some-bucket-name&#39;</span>,
</span></span><span style=display:flex><span>  Key: <span style=color:#a31515>&#39;image.jpg&#39;</span>,
</span></span><span style=display:flex><span>}).promise();
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#00f>const</span> resizedImage = <span style=color:#00f>await</span> sharp(originalImage.Body)
</span></span><span style=display:flex><span>  .resize(x, y)
</span></span><span style=display:flex><span>  .jpeg({ progressive: <span style=color:#00f>true</span> })
</span></span><span style=display:flex><span>  .toBuffer();
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>s3.putObject({
</span></span><span style=display:flex><span>  Bucket: <span style=color:#a31515>&#39;some-bucket-name&#39;</span>,
</span></span><span style=display:flex><span>  Key: <span style=color:#a31515>`optimized/</span><span style=color:#a31515>${</span>x<span style=color:#a31515>}</span><span style=color:#a31515>x</span><span style=color:#a31515>${</span>y<span style=color:#a31515>}</span><span style=color:#a31515>/image.jpg`</span>,
</span></span><span style=display:flex><span>  Body: resizedImage,
</span></span><span style=display:flex><span>  ContentType: <span style=color:#a31515>&#39;image/jpeg&#39;</span>,
</span></span><span style=display:flex><span>  ACL: <span style=color:#a31515>&#39;public-read&#39;</span>
</span></span><span style=display:flex><span>}).promise();
</span></span></code></pre><p>All this code was wrapped inside a web service with some additional security
checks and defensive coding to detect if key is missing on S3.<p>And at that point I needed to return placeholder images as a response in case
key is missing or x,y are not allowed by the server etc. I could have created
PNG in Gimp and just serve them but I wanted to respect aspect ratio and I
didn't want to return some mangled images.<blockquote><p>Main problem with finding a clean solution I could copy and paste and change a
bit was a task. API is changing constantly and there weren't clear examples or
I was unable to find them.</blockquote><h2 id=generating-placeholder-images-using-svg>Generating placeholder images using SVG</h2><p>What I ended up was using SVG to generate text and created image with sharp and
used composition to combine both layers. Response returned by this function is a
buffer you can use to either upload to S3 or save to local file.<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:#00f>const</span> generatePlaceholderImageWithText = <span style=color:#00f>async</span> (width, height, message) =&gt; {
</span></span><span style=display:flex><span>  <span style=color:#00f>const</span> overlay = <span style=color:#a31515>`&lt;svg width=&#34;</span><span style=color:#a31515>${</span>width - 20<span style=color:#a31515>}</span><span style=color:#a31515>&#34; height=&#34;</span><span style=color:#a31515>${</span>height - 20<span style=color:#a31515>}</span><span style=color:#a31515>&#34;&gt;
</span></span></span><span style=display:flex><span><span style=color:#a31515>    &lt;text x=&#34;50%&#34; y=&#34;50%&#34; font-family=&#34;sans-serif&#34; font-size=&#34;16&#34; text-anchor=&#34;middle&#34;&gt;</span><span style=color:#a31515>${</span>message<span style=color:#a31515>}</span><span style=color:#a31515>&lt;/text&gt;
</span></span></span><span style=display:flex><span><span style=color:#a31515>  &lt;/svg&gt;`</span>;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:#00f>return</span> <span style=color:#00f>await</span> sharp({
</span></span><span style=display:flex><span>    create: {
</span></span><span style=display:flex><span>      width: width,
</span></span><span style=display:flex><span>      height: height,
</span></span><span style=display:flex><span>      channels: 4,
</span></span><span style=display:flex><span>      background: { r: 230, g: 230, b: 230, alpha: 1 }
</span></span><span style=display:flex><span>    }
</span></span><span style=display:flex><span>  })
</span></span><span style=display:flex><span>    .composite([{
</span></span><span style=display:flex><span>      input: Buffer.from(overlay),
</span></span><span style=display:flex><span>      gravity: <span style=color:#a31515>&#39;center&#39;</span>,
</span></span><span style=display:flex><span>    }])
</span></span><span style=display:flex><span>    .jpeg()
</span></span><span style=display:flex><span>    .toBuffer();
</span></span><span style=display:flex><span>}
</span></span></code></pre><p>That is about it. Nothing more to it. You can change the color of the image by
changing <code>background</code> and if you want to change text styling you can adapt SVG
to your needs.<blockquote><p>Also be careful about the length of the text. This function positions text at
the center and adds <code>20px</code> padding on all sides. If text is longer than the
image it will get cut.</blockquote></div></div></main><footer><hr><div><h3>Want to comment or have something to add?</h3>You can write me an email at
<a href=mailto:m@mitjafelicijan.com>m@mitjafelicijan.com</a> or catch up
with me
<a href=https://telegram.me/mitjafelicijan target=_blank>on Telegram</a>.</div><hr><p>This website does not track you. Content is made available under
the <a href=https://creativecommons.org/licenses/by/4.0/ target=_blank rel=noreferrer>CC BY 4.0 license</a> unless specified
otherwise. Blog feed is available as <a href=/index.xml target=_blank>RSS feed</a>.</footer><script src=https://cdn.usefathom.com/script.js data-site=XHQARKXP defer></script>