The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Direct answer: For a deterministic PNG endpoint, render the card with Java2D: create a BufferedImage, draw the background, text and branding with Graphics2D, encode it with ImageIO, and return the bytes from a Spring MVC controller. Use Thymeleaf only when your design is already HTML/CSS; it produces markup, so you still need a browser-based renderer to create a PNG.
Choose the rendering approach first
Your choice affects dependencies, typography, latency and how much control you have over pixels.
| Approach | What it does | Advantages | Costs and risks |
|---|---|---|---|
| Java2D | Draws directly into a BufferedImage. |
Uses JDK APIs, has precise pixel control and no browser runtime. | You must implement wrapping, alignment, shaping and asset loading yourself. |
| Thymeleaf plus an HTML renderer | Fills an HTML/CSS template, then rasterizes it with a renderer selected by your project. | Natural for layouts already designed as web markup. | Requires the renderer, its fonts and its browser/runtime dependencies. Thymeleaf alone does not create PNG bytes. |
| Pre-rendered assets | Generates an image when a post is published and stores an immutable file or object-storage URL. | Removes expensive work from crawler requests and makes cache behavior predictable. | Needs a job, storage and an invalidation/versioning policy. |
For a first implementation, Java2D is usually the smallest reliable path. Keep image generation in a service; let the controller deal with routing, HTTP headers and encoding.
Set up a Spring Boot project
Dependencies
Add spring-boot-starter-web. If you choose the template route, also add spring-boot-starter-thymeleaf. Spring Initializr can create a project with Spring Web and Thymeleaf selected. With Maven, the relevant dependency declarations are:
#1 Best Overall
- Compatible with Nintendo Switch 2’s new GameChat mode
- Auto-Light Balance: RightLight boosts brightness by up to 50%, reducing shadows so you look your best—compared to previous-generation Logitech webcams (1)
- Privacy with a Slide: The integrated webcam cover makes it easy to get total, reliable privacy when you're not on a video call
- Built-In Mic: The built-in microphone lets others hear you clearly during video calls
- Easy Plug-And-Play: The Brio 101 works with most video calling platforms, including Microsoft Teams, Zoom and Google Meet—no hassle; it just works
<dependency>n <groupId>org.springframework.boot</groupId>n <artifactId>spring-boot-starter-web</artifactId>n</dependency>n<dependency>n <groupId>org.springframework.boot</groupId>n <artifactId>spring-boot-starter-thymeleaf</artifactId>n</dependency>
Put Thymeleaf files under src/main/resources/templates/ unless you changed the resolver prefix. The default suffix is .html.
Pick a stable image contract
Choose one canvas size for your site and use the same dimensions in the bytes and in the Open Graph metadata. The example below uses 1200×630 pixels as a site convention; it is not a protocol-mandated universal size. Keep the endpoint public over HTTPS, because crawlers must fetch it without a login.
Implement a Java2D renderer
Rendering service
This service caps user-controlled text, wraps it to the available width and loads all drawing resources from controlled locations. Replace the sample colors and text with your brand system.
Recommended Free Tools
package com.example.og;nnimport java.awt.BasicStroke;nimport java.awt.Color;nimport java.awt.Font;nimport java.awt.FontMetrics;nimport java.awt.Graphics2D;nimport java.awt.RenderingHints;nimport java.awt.image.BufferedImage;nimport org.springframework.stereotype.Service;nn@Servicenpublic class OgImageService {n public static final int WIDTH = 1200;n public static final int HEIGHT = 630;n private static final int MAX_TITLE_CHARS = 140;nn public BufferedImage render(String title, String subtitle) {n String safeTitle = limit(title, MAX_TITLE_CHARS, "Untitled post");n String safeSubtitle = limit(subtitle, 180, "");nn BufferedImage image = new BufferedImage(n WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);n Graphics2D g = image.createGraphics();n try {n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,n RenderingHints.VALUE_ANTIALIAS_ON);n g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,n RenderingHints.VALUE_TEXT_ANTIALIAS_ON);n g.setColor(new Color(18, 24, 38));n g.fillRect(0, 0, WIDTH, HEIGHT);nn g.setColor(new Color(71, 130, 218));n g.fillRoundRect(72, 72, 120, 12, 6, 6);nn Font titleFont = new Font("SansSerif", Font.BOLD, 64);n Font subtitleFont = new Font("SansSerif", Font.PLAIN, 28);n g.setColor(Color.WHITE);n drawWrapped(g, safeTitle, titleFont, 72, 210, 1050, 78, 3);nn if (!safeSubtitle.isBlank()) {n g.setColor(new Color(190, 201, 219));n drawWrapped(g, safeSubtitle, subtitleFont, 72, 500, 1050, 38, 2);n }n } finally {n g.dispose();n }n return image;n }nn private static int drawWrapped(Graphics2D g, String text, Font font,n int x, int y, int maxWidth,n int lineHeight, int maxLines) {n g.setFont(font);n FontMetrics metrics = g.getFontMetrics();n String[] words = text.trim().split("\\s+");n StringBuilder line = new StringBuilder();n int lineNumber = 0;n for (String word : words) {n String candidate = line.length() == 0n ? word : line + " " + word;n if (metrics.stringWidth(candidate) > maxWidthn && line.length() > 0) {n g.drawString(line.toString(), x, y + lineNumber * lineHeight);n line.setLength(0);n line.append(word);n if (++lineNumber == maxLines - 1) break;n } else {n line = new StringBuilder(candidate);n }n }n if (lineNumber < maxLines && line.length() > 0) {n g.drawString(line.toString(), x, y + lineNumber * lineHeight);n lineNumber++;n }n return lineNumber;n }nn private static String limit(String value, int max, String fallback) {n if (value == null || value.isBlank()) return fallback;n String normalized = value.strip();n return normalized.length() <= maxn ? normalized : normalized.substring(0, max - 1) + "…";n }n}
For production typography, package specific font files and register them with GraphicsEnvironment rather than relying on whatever fonts happen to be installed on a host. Test every supported locale: missing glyphs, right-to-left scripts, combining marks and different word-breaking rules can change the layout. If your audience needs complex shaping, verify the chosen Java font and layout behavior before shipping.
Return PNG bytes from a controller
The controller below uses the slug as sample content. In a real application, load the post title and description from your repository and return a normal 404 when the slug does not exist.
Rank #2
- Compatible with Nintendo Switch 2’s new GameChat mode
- Crisp HD 720p/30 fps video calls with diagonal 55° field of view and auto light correction. Compatible with popular platforms including Skype and Zoom.
- The built-in noise-reducing mic makes sure your voice comes across clearly up to 1.5 meters away, even if you’re in busy surroundings.
- C270’s RightLight 2 feature adjusts to lighting conditions, producing brighter, contrasted images to help you look good in all your conference calls.
- The adjustable universal clip lets you attach the camera securely to your screen or laptop, or fold the clip and set the webcam on a shelf. You’re always ready for your next video call.
package com.example.og;nnimport java.io.ByteArrayOutputStream;nimport java.io.IOException;nimport java.time.Duration;nimport java.awt.image.BufferedImage;nimport javax.imageio.ImageIO;nimport org.springframework.http.CacheControl;nimport org.springframework.http.MediaType;nimport org.springframework.http.ResponseEntity;nimport org.springframework.web.bind.annotation.GetMapping;nimport org.springframework.web.bind.annotation.PathVariable;nimport org.springframework.web.bind.annotation.RestController;nn@RestControllernpublic class OgImageController {n private final OgImageService images;nn public OgImageController(OgImageService images) {n this.images = images;n }nn @GetMapping(value = "/og/{slug}.png", produces = MediaType.IMAGE_PNG_VALUE)n public ResponseEntity<byte[]> og(@PathVariable String slug) throws IOException {n String title = slug.replace('-', ' ');n BufferedImage image = images.render(title, "Example site");n try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {n if (!ImageIO.write(image, "png", out)) {n throw new IOException("No PNG writer is available");n }n return ResponseEntity.ok()n .cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePublic())n .contentType(MediaType.IMAGE_PNG)n .body(out.toByteArray());n }n }n}
The one-hour cache value is only an example policy. For immutable URLs containing a content version or hash, a much longer cache lifetime is appropriate. For mutable slugs, choose a shorter lifetime or purge the cache when a title changes.
Publish the Open Graph metadata
Place the tags in the HTML <head> of the page being shared. The URL must be absolute, HTTPS and reachable without authentication. The image properties describe the actual response, not the intended design.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
<meta property="og:image" th:content="${ogImageUrl}">n<meta property="og:image:secure_url" th:content="${ogImageUrl}">n<meta property="og:image:type" content="image/png">n<meta property="og:image:width" th:content="${ogImageWidth}">n<meta property="og:image:height" th:content="${ogImageHeight}">n<meta property="og:image:alt" th:content="${ogImageAlt}">
og:image:alt is a description of what is in the image, not a caption. Generate it from safe post data and escape it through the template engine. Supply ogImageWidth and ogImageHeight from the same constants used by the renderer so a later size change cannot leave stale metadata.
Build the URL in the view model
model.addAttribute("ogImageUrl",n ServletUriComponentsBuilder.fromCurrentContextPath()n .path("/og/{slug}.png")n .buildAndExpand(post.slug())n .toUriString());nmodel.addAttribute("ogImageWidth", OgImageService.WIDTH);nmodel.addAttribute("ogImageHeight", OgImageService.HEIGHT);nmodel.addAttribute("ogImageAlt", "Social preview for " + post.title());
Thymeleaf supports context-relative and absolute URL expressions. If your application sits behind a proxy, configure forwarded headers correctly or construct the canonical public origin from trusted configuration; never accept an arbitrary host header for this URL.
Use Thymeleaf when the design is HTML-first
Spring Boot auto-configures a SpringTemplateEngine when Thymeleaf is present. A dedicated og-image.html can contain the card layout and inline or bundled CSS:
Rank #3
- 【Full HD 1080P Webcam】Powered by a 1080p FHD two-MP CMOS, the NexiGo N60 Webcam produces exceptionally sharp and clear videos at resolutions up to 1920 x 1080 with 30fps. The 3.6mm glass lens provides a crisp image at fixed distances and is optimized between 19.6 inches to 13 feet, making it ideal for almost any indoor use.
- 【Wide Compatibility】Works with USB 2.0/3.0, no additional drivers required. Ready to use in approximately one minute or less on any compatible device. Compatible with Mac OS X 10.7 and higher / Windows 7, 8, 10 & 11 / Android 4.0 or higher / Linux 2.6.24 / Chrome OS 29.0.1547 / Ubuntu Version 10.04 or above. Not compatible with XBOX/PS4/PS5.
- 【Built-in Noise-Cancelling Microphone】The built-in noise-canceling microphone reduces ambient noise to enhance the sound quality of your video. Great for Zoom / Facetime / Video Calling / OBS / Twitch / Facebook / YouTube / Conferencing / Gaming / Streaming / Recording / Online School.
- 【USB Webcam with Privacy Protection Cover】The privacy cover blocks the lens when the webcam is not in use. It's perfect to help provide security and peace of mind to anyone, from individuals to large companies. 【Note:】Please contact our support for firmware update if you have noticed any audio delays.
- 【Wide Compatibility】Works with USB 2.0/3.0, no additional drivers required. Ready to use in approximately one minute or less on any compatible device. Compatible with Mac OS X 10.7 and higher / Windows 7, 10 & 11, Pro / Android 4.0 or higher / Linux 2.6.24 / Chrome OS 29.0.1547 / Ubuntu Version 10.04 or above. Not compatible with XBOX/PS4/PS5.
<!doctype html>n<html xmlns:th="http://www.thymeleaf.org">n<body style="margin:0;width:1200px;height:630px;background:#121826">n <main style="padding:72px;color:white;font-family:Arial,sans-serif">n <div style="height:12px;width:120px;background:#4782da"></div>n <h1 th:text="${title}" style="font-size:64px;line-height:1.15">Title</h1>n <p th:text="${subtitle}" style="font-size:28px;color:#bec9db">Subtitle</p>n </main>n</body>n</html>
Thymeleaf renders this to HTML; it does not rasterize it. Add the HTML-to-image renderer your team has selected and document its runtime, sandbox, font installation and upgrade requirements. Keep the template dimensions fixed, avoid remote assets, and make sure the renderer waits for fonts and images before taking the shot. Java2D remains preferable when a browser runtime would be operationally excessive.
Choose synchronous, cached or pre-generated delivery
Synchronous generation
Generate on the first crawler request when traffic is low and cards are small. Bound all text and avoid fetching arbitrary URLs during rendering. A slow database call or font load directly increases crawler latency.
Application cache
Cache by a key containing the post identifier and a renderer/template version. Include the version so a redesign cannot serve old pixels forever. Cache the encoded bytes, not only the BufferedImage, when PNG encoding is a measurable part of the request.
Pre-generation and immutable URLs
Generate when content is published or updated, store the PNG in object storage, and expose a URL containing a content version. This keeps social crawlers away from your application servers and makes long-lived HTTP caching safe. Ensure a failed generation marks the job as failed and does not publish an HTML error page at an image URL.
Security, correctness and accessibility checks
- Allow only a slug or database identifier; never turn request parameters into filesystem paths, font paths or remote URLs.
- Escape title, subtitle and alt text in HTML templates. In Java2D, treat them as text only.
- Set
Content-Typeto match the encoded bytes. A PNG endpoint must not return an HTML exception page with an image media type. - Define fallback text for deleted or missing records and return a normal HTTP error for an unknown slug.
- Load logos and fonts from versioned classpath resources or trusted storage.
- Use a deterministic renderer for a given content and renderer version; this makes cache invalidation and debugging possible.
- Check the final public URL from outside your network, follow redirects, and verify that the downloaded bytes are a valid image.
- Inspect cards on the social platforms your readers use. Each platform can cache metadata independently, so test after publishing a versioned URL.
Performance and reliability notes
There is no universal published benchmark for Spring OG rendering. Measure your own p50 and p95 generation time, encoded byte size, heap usage and cache-hit ratio with representative titles and locales. Reuse immutable fonts and logos; do not read them from disk for every request. Keep a timeout around database access, and isolate a browser renderer in a bounded worker pool if you use Thymeleaf plus HTML capture. Rate-limit public endpoints if attackers can force arbitrary cache misses.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Rank #4
- 1080P Webcam with Cover for Video Calls - EMEET computer webcam provides design and Optimization for professional video streaming. Realistic 1920 x 1080p video, 5-layer anti-glare lens, providing smooth video. C960 computer camera delivers 1920x1080 video with fixed focus (11.8–118.1 inches), so as to provide a clearer image. C960 USB webcam has a cover and can be removed automatically to meet your needs for privacy. For optimal image performance, use the webcam in a well-lit environment.
- Built-in 2 Omnidirectional Mics - EMEET webcam with microphone for desktop features 2 built-in omnidirectional microphones, picking up your voice to create clear audio for communication. When installing the webcam, select EMEET C960 as the default microphone input device in your computer and video applications and select C960 as the default device in Zoom/Teams and ensure microphone permissions are enabled for proper use. Please note that C960 does not include built-in speakers.
- Automatic Light Adjustment - Automatic exposure adjustment is applied in EMEET HD webcam 1080p so that the streaming webcam can deliver stable image performance. EMEET C960 camera for computer also features color adjustment and exposure optimization to help you look your best. For optimal video quality, it is recommended to use the webcam in normal or well-lit environments and select suitable video settings in your application. Proper lighting helps achieve a clearer and more balanced image.
- Plug-and-Play & Upgraded USB Connectivity - New C960 webcam features both USB Type-A & A-to-C adapter connections for wider compatibility. For stable performance, connect the webcam directly to the computer's main USB port and ensure the device is recognized correctly. If a hub or docking station is used, please ensure it provides sufficient power and stable data transmission, as limited ports may affect performance. 90° wide-angle lens captures more participants without frequent adjustments.
- High Compatibility & Multi Application - C960 webcam for laptop is compatible with Windows 10/11, macOS 10.14+, and Android TV 7.0+. Not supported: Windows Hello, TVs, tablets, or game consoles. It works with Zoom, Teams, Facetime, Google Meet, YouTube and more. Please select C960 webcam as the default camera and microphone device in your application and ensure camera/microphone permissions are enabled, especially on macOS. (Tips: Incompatible with Windows Hello)
PNG is lossless and convenient for text. If bandwidth matters, the same pipeline can encode JPEG or WebP, but update the media type and og:image:type together and verify that the target social platforms accept the format you choose. Do not claim a size or format is universally preferred without testing your audience's platforms.
Troubleshooting
The crawler receives a 404 or an HTML page
Check the absolute URL in the rendered page source, proxy routing and authentication middleware. Request the image with curl -I and confirm a 200 response with Content-Type: image/png. Return errors through the normal Spring exception path rather than writing an error document to the image stream.
Text is clipped or overlaps
Log the measured title width, lower the font size or increase the available region, and enforce a maximum line count. Test unusually long words, punctuation and titles containing emoji. A character-count limit alone is not a layout limit because glyph widths differ.
Accents or non-Latin characters appear as boxes
The runtime is missing a glyph. Bundle a font covering your supported scripts, register it at startup and test fallback behavior. For right-to-left or complex-script content, verify shaping and line direction rather than assuming Latin wrapping works.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchThe card shows an old design
Identify whether the stale copy is your HTTP cache, an object-storage cache or a social platform cache. Bump the image URL version when the template changes, or purge the layer you control. Keep the metadata dimensions synchronized with the new bytes.
Best Value
- Compatible with Nintendo Switch 2’s new GameChat mode
- HD lighting adjustment and autofocus: The Logitech webcam automatically fine-tunes the lighting, producing bright, razor-sharp images even in low-light settings. This makes it a great webcam for streaming and an ideal web camera for laptop use
- Advanced capture software: Easily create and share video content with this Logitech camera that is suitable for use as a desktop computer camera or a monitor webcam
- Stereo audio with dual mics: Capture natural sound during calls and recorded videos with this 1080p webcam, great as a video conference camera or a computer webcam
- Full HD 1080p video calling and recording at 30 fps. You'll make a strong impression with this PC webcam that features crisp, clearly detailed, and vibrantly colored video
Thymeleaf output is correct but the PNG is blank
The rasterizer may have captured before fonts, images or styles finished loading, or the template may reference resources unavailable in its sandbox. Inline critical CSS, use local assets, wait for the required selector or network idle, and capture a fixed viewport matching the template dimensions.
Memory usage grows under load
Always dispose each Graphics2D, close output streams, and bound concurrent browser jobs. Avoid retaining large images in unbounded maps; cache encoded bytes with an explicit maximum size and eviction policy.
Or skip the browser setup
If you have an HTML card page and want a service to capture it, ScreenshotNeo is the first alternative to try: it removes consent banners, newsletter popups and chat widgets before capture, bills only clean shots, and its paid plans start at the lowest listed price.
Expose a public, deterministic card URL such as https://your-site.example/og-card/my-post, then call the API. See the ScreenshotNeo API documentation for all parameters.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://your-site.example/og-card/my-post -o shot.webp
import requestsnr = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://your-site.example/og-card/my-post"}, timeout=90)nr.raise_for_status()nopen("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://your-site.example/og-card/my-post' });nconst res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);nif (!res.ok) throw new Error(`HTTP ${res.status}`);nconst data = Buffer.from(await res.arrayBuffer());nawait fs.promises.writeFile('shot.webp', data);
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. Failed loads, bot checks, CAPTCHAs, blank pages, timeouts and cache hits are not billed, and response headers identify the page verdict and billing result. Every plan includes the features; the Free plan includes 1,000 shots per month with no card, while paid pricing is Starter $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000 and Business $249 for 1,000,000. Yearly billing provides two months free. Create a free ScreenshotNeo account to try the 1,000 monthly shots without adding a card.
Frequently Asked Questions
Can one endpoint serve different image formats?
Yes. Keep the layout service independent from encoding, choose the encoder from a trusted route or configuration, and make the response media type and Open Graph type describe the bytes actually returned. Do not let a request parameter select arbitrary codecs.
Where should a logo be loaded from in a containerized deployment?
Package the approved logo as a versioned classpath resource or fetch it from a controlled object-storage location during deployment. Avoid downloading a logo during each crawler request, which adds latency and creates an external failure dependency.
How can I roll out a new card design safely?
Render the new template under a new renderer version, compare representative titles and locales, then switch metadata URLs to the new version. Retain the old version until existing cached URLs have expired.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

