PHP

Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file

CK CK 3788 
Created at
Updated at  
974 0 0

Creating images dynamically within HTML can be a powerful tool for web developers, allowing for personalized and customizable content. By leveraging PHP's GD library, developers can generate images on-the-fly based on user input or other dynamic data, without the need to store files on the server. In this article, we'll explore how to generate an image with specified text, width, and height, positioning the text at the center of the image.

Introduction:

In modern web development, the ability to dynamically generate images can greatly enhance user experiences. Whether it's generating personalized avatars, dynamic charts, or customized memes, dynamically generated images can add a layer of interactivity and personalization to websites and web applications.

Generating Images with PHP's GD Library:

PHP's GD library provides a wide range of functions for creating and manipulating images. One of its key features is the ability to generate images on-the-fly, allowing developers to create images dynamically in response to user actions or other inputs.

Creating Images with Text:

Let's dive into a basic example of generating an image with text using PHP's GD library. We'll create a function that takes the text, width, and height as parameters, and positions the text at the center of the image.

<?php
// Function to create an image with text in the center
function createImage($text, $width, $height) {
    // Create a blank image with specified dimensions
    $image = imagecreatetruecolor($width, $height);
    
    // Set background color to white
    $bgColor = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bgColor);
    
    // Set text color to black
    $textColor = imagecolorallocate($image, 0, 0, 0);
    
    // Calculate text width and height
    $font = 4; // adjust font size as needed
    $textWidth = imagefontwidth($font) * strlen($text);
    $textHeight = imagefontheight($font);
    
    // Calculate text position to center it
    $x = ($width - $textWidth) / 2;
    $y = ($height - $textHeight) / 2;
    
    // Write text onto the image
    imagestring($image, $font, $x, $y, $text, $textColor);
    
    // Output the image as a base64 encoded blob
    ob_start();
    imagepng($image);
    $imageData = ob_get_clean();
    imagedestroy($image);
    
    $base64 = base64_encode($imageData);
    
    return $base64;
}

// Example usage
$text = "Hello, World!";
$width = 200;
$height = 100;

$imageBlob = createImage($text, $width, $height);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image with Text</title>
</head>
<body>
    <img src="data:image/png;base64,<?= $imageBlob ?>" alt="Generated Image">
</body>
</html>

This code creates a PNG image with the specified text at the center, converts it to a base64 encoded blob, and embeds it directly into an HTML <img> tag. Adjust the parameters like $text, $width, and $height as needed.

Generating images dynamically in HTML using PHP's GD library opens up a world of possibilities for web developers. By creating images on-the-fly, developers can deliver personalized and interactive content to users without the need to store files on the server. Whether it's generating avatars, charts, or custom memes, dynamically generated images can enhance the user experience and add a touch of interactivity to any web application.

Tags Base64-Encoding Dynamic-Image GD-Library HTML PHP Web-Development Facebook X
Comments 0
Similar posts
  1. Mastering Excel Data Importation in PHP
    555
  2. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    596
  3. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  4. How do we make better SEO with schema.org?
    424
  5. Setup Apache+PHP+MySQL on Centos 6.7
    605
  6. PHP Code can know the current OS is windows or not
    584
  7. Checking similarity between two strings in PHP
    674
  8. Simple PHP calendar
    478
  9. Simple PHP code performance measuring example
    792
  10. Convert plain HTML to XHTML
    453
  11. To block copy & paste on your blog content
    901
  12. GD library version in PHP
    505
  13. JSON format control in PHP
    693
  14. mysql optimization – if you are using Word Press, do not turn off persistent connection
    593
  15. File downloading function through PHP code
    532
  16. Image file resizing in PHP
    562
  17. Apache server unstable detection and the related server(mysql, apache) restart automatically
    538
  18. Shake your browser window by Javascript
    936
  19. Function can extract file name in string having full path in PHP
    568
  20. How to create private URL on S3/CloudFront with time-limit ?
    919
  21. Uploading files to Amazon S3 with REST API in PHP
    842
  22. Human readable random string for captchas in PHP
    560
  23. How to get the duration between days in PHP
    423
  24. Date format validation in PHP
    571
  25. PHP function converts new line to BR tag
    562
  26. Email Validation Snipet in PHP
    381
  27. PHP socket programming to get content with post method
    410
  28. Photoshop script programming in Javascript
    531
  29. To compare two HTML tables on web page in real time
    515
  30. To hide/show area of web page without re-loading a page
    1,021
  1. PHP Code to Fetch current Coinbase Assets (Balances)
    440
  2. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    364
  3. Google Single Sign-On implementation with PHP
    1,374
  4. PHP Superglobal Variables do not require additional syntax to access it
    2,638
  5. Run Python Code with Virtual Environment in PHP
    673
  6. PHP Simplified Operators
    318
  7. PHP Heredoc (aka Nowdoc)
    439
  8. PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics
    1,809
  9. WordPress Remote Posting with PHP
    1,686
  10. Google BigQuery Example to converted Nested FIelds in JSON
    459
  11. Verifying Apple In-App Purchase validation receipt with PHP
    1,787
  12. Useful code for file-based Unit Test in PHP
    500
  13. Function Overloading Implementation in PHP with Magic Mathods
    1,757
  14. PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL
    1,672
  15. How do I find php.ini on Mac?
    493
  16. How do I determine the client IP type (IPv4/IPv6) in PHP
    834
  17. What is 302 Found Redirection in HTTP 1.1?
    491
  18. Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records
    620
  19. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    307
  20. Apache Kafka Explained: Powering Netflix, Building with PHP
    492
  21. Array of arguments passed to script in PHP
    90
  22. Bob Jenkins' One-At-A-Time hashing algorithm in PHP
    53
  23. 32bits simple hash function in PHP
    40
  24. PHP Code Compression Tool by removing whitespace, strips comments - PHP Minifier/Compressor
    1,415
  25. mcrypt missing when using phpMyAdmin on Centos 6.7
    550
  26. How to set AUTO_INCREMENT ID in mySQL ?
    607
  27. Parsing XML in PHP
    1,192
  28. Unzip a ZIP file in PHP
    503
  29. How to get browser information in PHP?
    855
  30. Get Remote IP Address in PHP
    499
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    20,969
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Invalid Auction Storms in Ad Tech
    98
  8. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  9. The Two Clocks of Ad Server Architecture
    70
  10. Frequency Cap Architecture Overview
    515
  11. Collecting Proof-of-Play from 100,000 Screens
    146
  12. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  13. What is RedisVL?
    109
  14. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    231
  15. TPU & GPU Cluster Management Tools
    245
  16. The Concept of Scaffolding in AI Agents
    234
  17. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  21. Machine Learning: Training vs. Ranking
    222
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  24. Designing a Data Curation System Around a Vector Database
    221
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  29. Understanding Data Lineage
    262
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    167