Saved the Day - Handling Large Images in the Browser" />
A client uploaded 28 images, each around 5800 x 9500 pixels and 28 MB in size. When attempting to display these images in the browser, the entire tab froze - even refusing to close - for a solid 10 minutes. And this was on a high-end machine with a Ryzen 9 CPU and an RTX 4080 GPU, not a tiny laptop.
Here’s The Situation
In our CMS (Grace Web), when an admin uploads a file - be it a picture or a video - we display it immediately after the upload finishes. It's great for UX - it confirms the upload was successful, they uploaded what they intended to, and it shows responsiveness of the UI for better feel.
But with these massive images, the browser could barely display them and froze up.
It's important to note that the issue wasn't with the upload itself but with displaying these large images. Rendering 28 huge images simultaneously and one by one was just too much. Even on a blank page, it's just... nope.
Why Did This Happen (Deep Dive)?
Anytime you display a picture in an tag, the browser goes through an entire process that employs the CPU, RAM, GPU, and sometimes the drive - sometimes even cycling through this process multiple times before the picture is displayed during image loading and layout recalculations. It goes through calculating pixels, transferring data among hardware, interpolating algorithms, etc. For a browser, it’s a significant process.
The Brainstormed Solutions
We considered several options:
-
Resize Immediately After Upload and Display Thumbnail
- Issue: Resizing could take too long and isn't guaranteed to be instantaneous, especially if the resizing queue isn't empty - results in not-a-responsive system.
-
Check File Sizes and Display Only Their Names for Large Files
- Issue: This would detract from the user experience, especially for those who require greater control and checks of any media material (incidentally, those are often the same ones with large files).
Neither of these solutions felt usable. We didn't want to limit our admins' ability to upload whatever they needed, nor did we want to compromise on the user experience.
Lightbulb! Using
I recalled that the
Testing the Theory
We decided to replace the elements with
const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); // img.src = URL.createObjectURL(file); // Use this if you're working with uploaded files img.src = filesroot + data.file_path; // Our existing file path img.onload = function() { // Resize canvas to desired size (for preview) canvas.width = 80 * (img.width / img.height); // Adjust scaling as needed canvas.height = 80; // Draw the image onto the canvas, resizing it in the process ctx.drawImage(img, 0, 0, canvas.width, canvas.height); file_div.innerHTML = ''; // Prepared <div> in UI to display the thumbnail file_div.appendChild(canvas); }; <h3> The Results </h3> <p>The improvement was immediate and dramatic! Not only did the browser handle the 28 large images without any hiccups, but we also pushed it further by loading <strong>120 MB images</strong> measuring <strong>28,000 x 17,000 pixels</strong>, and it still worked as if it was a tiny icon.</p> <h3> Where Is the Difference? </h3> <p>Using the <canvas> element, the drawing is entirely in the hands of the GPU, and those chips are literally made for this task.</canvas></p> <ul> <li> <img alt="How Saved the Day - Handling Large Images in the Browser" > still attempts to render 28,000 * 17,000 = 476,000,000 pixels.</li> <li>This <canvas> draws only 80 * 80 = 6,400 pixels.</canvas> </li> </ul> <p>By resizing the image within the <canvas> to a small preview size, we're drastically reducing the amount of data the browser needs to process - send hundreds of millions of pixels to GPU and get back thousands, a great deal, right?</canvas></p> <h2> Next Steps </h2> <p>Given this success, we're now considering replacing <img alt="How Saved the Day - Handling Large Images in the Browser" > with <canvas> in other parts of our application, particularly in admin screens that display around 250 images at once. While these images are already properly resized, we're curious to see if using <canvas> can offer even better performance.</canvas></canvas></p> <p>We'll be conducting testing and benchmarking to measure any performance gains. I'll be sure to share our findings in a future article.</p> <h2> Important Caveats </h2> <p>While using <canvas> worked wonders for our specific use case, I must note that you <strong>should not use <canvas> for displaying images on public-facing parts of websites</canvas></strong>. Here's why:</canvas></p> <ul> <li> <strong>Accessibility</strong>: <img alt="How Saved the Day - Handling Large Images in the Browser" > elements are readable by screen readers, aiding visually impaired users.</li> <li> <strong>SEO</strong>: Search engines index images from <img alt="How Saved the Day - Handling Large Images in the Browser" > tags, which can improve your site's visibility. (In the same way, AI-training scrapers "index" the images, too. Well, what can you do...)</li> <li> <img alt="How Saved the Day - Handling Large Images in the Browser" > with <picture> can be used to automatically detect pixel density and show bigger or smaller pictures for a perfect fit—<canvas> can’t. I wrote an article on how to build your .</canvas></picture> </li> </ul> <p>For public websites, it's best to properly resize images on the server side before serving them to users. If you're interested in how to automate image resizing and optimization, I wrote an article on that topic you might find useful.</p> <h2> Conclusion </h2> <p><strong>I love optimization!</strong> Even though we are moving towards local high-performance hardware each day, by optimizing - even when "it's good, but can be better" - we could prevent issues like this from the beginning.</p> <p>This approach is not standard. And I don’t care for standards very much. They are often treated as hard rules, but they are just guidelines. This solution fits. We do not have clients with ancient devices without solid <canvas> support. So, even though now we have more code to manage, multiple ways of displaying pictures, it’s a perfect fit, and that’s what matters!</canvas></p> <p><strong>Do you have some similar experiences? How did you handle it? Feel free to share your experiences or ask questions in the comments below!</strong></p> </div>
The above is the detailed content of How Saved the Day - Handling Large Images in the Browser. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
