Improving Image Downloads in Breniapp
Introduction
In Breniapp, we recently tackled an issue where downloaded images were not reflecting the complete visual output displayed on screen. Specifically, text and logo overlays, which were rendered using HTML and CSS, were missing from the downloaded image, resulting in users receiving only the base image.
The Problem
The original download implementation was simply fetching the raw base image URL. This approach bypassed the dynamically added HTML/CSS elements, such as text and logos, that were overlaid on the image within the application's canvas. Consequently, the downloaded image lacked crucial visual information.
The Solution
To address this, we switched to capturing the entire canvas container as a bitmap before initiating the download. This ensures that all visual elements, including the base image and any HTML/CSS overlays, are included in the final downloaded image.
We utilized html2canvas to render a high-fidelity image of the canvas complete with overlays. The generated image data is then used to trigger the download.
<?php
use Symfony\Component\Process\Process;
class ImageService
{
public function captureCanvas(string $elementId): string
{
$command = ['node', 'capture.js', $elementId];
$process = new Process($command);
$process->run();
if (!$process->isSuccessful()) {
throw new \Exception($process->getErrorOutput());
}
return $process->getOutput();
}
}
Key Improvements
- Complete Visual Representation: Downloads now accurately reflect the on-screen display, including all text and logo overlays.
- Enhanced User Experience: Users receive a more complete and useful image, eliminating the need for manual editing or workarounds.
Lessons Learned
When dealing with dynamic content, ensure that your capture mechanism accounts for all rendered elements, not just the underlying resources. Tools like html2canvas can be invaluable for capturing complex, visually rich content.