DEV Community

sir lu
sir lu

Posted on

Resize and Pad AI Images for Social Media Aspect Ratios with HTML5 Canvas

AI-generated art often outputs standard 1:1 or 16:9 aspect ratios. Adapting these images for social platforms (Instagram 4:5, YouTube Banners, Twitter Headers) without awkward cropping requires canvas padding and blur backgrounds.

Creating a Blurred Padding Background

function resizeWithBlurredBackground(sourceImg, targetWidth, targetHeight) {
  const canvas = document.createElement('canvas');
  canvas.width = targetWidth;
  canvas.height = targetHeight;
  const ctx = canvas.getContext('2d');

  // 1. Draw scaled background with CSS blur filter
  ctx.filter = 'blur(20px)';
  ctx.drawImage(sourceImg, 0, 0, targetWidth, targetHeight);
  ctx.filter = 'none';

  // 2. Draw sharp original image centered on top
  const scale = Math.min(targetWidth / sourceImg.width, targetHeight / sourceImg.height);
  const x = (targetWidth - sourceImg.width * scale) / 2;
  const y = (targetHeight - sourceImg.height * scale) / 2;

  ctx.drawImage(sourceImg, x, y, sourceImg.width * scale, sourceImg.height * scale);
  return canvas.toDataURL('image/png');
}

Enter fullscreen mode Exit fullscreen mode

This technique ensures images match social platform dimensions while maintaining aesthetic composition.


Resize AI images for social platforms with custom aspect ratios using Canvas Resizer.

Top comments (0)