DEV Community

gleamso
gleamso

Posted on

10 Advanced OG Image Techniques I Learned Building gleam.so 🔍

Building an OG image generator taught me tricks that aren't widely documented. Here are 10 advanced techniques that will level up your OG image game.

1. Dynamic Font Scaling 📏

const calculateFontSize = (text: string, maxWidth: number): number => {
  const baseSize = 72;
  const ratio = maxWidth / measureTextWidth(text, baseSize);
  return Math.floor(baseSize * ratio);
};

// Usage
<text 
  fontSize={calculateFontSize(title, 600)}
  textAnchor="middle"
>
  {title}
</text>
Enter fullscreen mode Exit fullscreen mode

2. Smart Image Composition 🎨

const composeImage = async (background: string, overlay: string) => {
  return sharp(background)
    .composite([{
      input: overlay,
      blend: 'overlay',
      gravity: 'center'
    }])
    .modulate({
      brightness: 1.1,
      saturation: 0.8
    })
    .toBuffer();
};
Enter fullscreen mode Exit fullscreen mode

3. Gradient Text Effect 🌈

const GradientText = ({ text }) => (
  <svg>
    <defs>
      <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
        <stop offset="0%" stopColor="#FF6B6B" />
        <stop offset="100%" stopColor="#4ECDC4" />
      </linearGradient>
    </defs>
    <text fill="url(#gradient)">{text}</text>
  </svg>
);
Enter fullscreen mode Exit fullscreen mode

4. Automatic Content Balancing ⚖️

interface Layout {
  title: string;
  image?: string;
  logo?: string;
}

const balanceLayout = (layout: Layout): LayoutConfig => {
  const hasImage = !!layout.image;
  const hasLogo = !!layout.logo;

  return {
    titleSize: hasImage ? 'medium' : 'large',
    titlePosition: hasImage ? 'left' : 'center',
    imageWidth: hasImage ? '40%' : '0',
    padding: hasLogo ? '80px' : '60px'
  };
};
Enter fullscreen mode Exit fullscreen mode

5. Responsive Text Wrapping 📝

const wrapText = (text: string, maxWidth: number, fontSize: number) => {
  const words = text.split(' ');
  const lines = [];
  let currentLine = [];

  words.forEach(word => {
    const testLine = [...currentLine, word].join(' ');
    if (measureWidth(testLine, fontSize) <= maxWidth) {
      currentLine.push(word);
    } else {
      lines.push(currentLine.join(' '));
      currentLine = [word];
    }
  });

  lines.push(currentLine.join(' '));
  return lines;
};
Enter fullscreen mode Exit fullscreen mode

6. Edge Caching Strategy 🚀

export const config = {
  runtime: 'edge',
  headers: {
    'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400'
  }
};

const generateCacheKey = (params: Params): string => {
  const sorted = Object.keys(params)
    .sort()
    .reduce((acc, key) => ({
      ...acc,
      [key]: params[key]
    }), {});

  return createHash('sha256')
    .update(JSON.stringify(sorted))
    .digest('hex');
};
Enter fullscreen mode Exit fullscreen mode

7. Fallback System 🛟

class OGGenerator {
  async generate(config: Config) {
    try {
      return await this.primaryGeneration(config);
    } catch (error) {
      console.error('Primary generation failed:', error);
      try {
        return await this.fallbackGeneration(config);
      } catch (fallbackError) {
        console.error('Fallback failed:', fallbackError);
        return this.staticFallback;
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

8. Memory Management 🧠

const optimizeMemory = {
  beforeGeneration: () => {
    if (global.gc) global.gc();
  },

  cleanup: async (buffer: Buffer) => {
    buffer = null;
    if (global.gc) global.gc();

    await new Promise(resolve => setTimeout(resolve, 100));
  }
};
Enter fullscreen mode Exit fullscreen mode

9. Loading State Optimization ⚡

const PreviewSystem = () => {
  const [preview, setPreview] = useState<string>();
  const generateDebounced = useCallback(
    debounce(async (config) => {
      const result = await generatePreview(config);
      setPreview(result);
    }, 300),
    []
  );

  return (
    <div className="preview">
      {preview ? (
        <img src={preview} alt="OG Preview" />
      ) : (
        <LoadingPlaceholder />
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

10. Quality Assurance System 🎯

const validateOGImage = async (url: string) => {
  const tests = [
    checkDimensions,
    checkFileSize,
    checkLoadTime,
    checkContrast,
    checkTextReadability
  ];

  const results = await Promise.all(
    tests.map(test => test(url))
  );

  return results.every(result => result.passed);
};
Enter fullscreen mode Exit fullscreen mode

Real-World Impact 📊

These techniques helped achieve:

  • Generation time: 450ms
  • Cache hit rate: 85%
  • Failed generations: <0.5%
  • Memory usage: 90MB

Implementation Tips 💡

  1. Start with fallbacks
  2. Monitor performance
  3. Cache aggressively
  4. Test across platforms

Community Discussion 🤝

What challenges are you facing with OG images? Share your use cases in the comments!

Black Friday Special ✨

Try all these techniques implemented in gleam.so - now 75% off! Create perfect OG images instantly.

Image description


Part of the "Making OpenGraph Work" series. Follow for more advanced web development insights!

Top comments (0)