Core JavaScript

AJAX Get a PHP Image

This JavaScript program shows how to fetch a PHP generated image via an AJAX call.

XoaxAjaxGetPhpImage.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript AJAX Example</title>
    <style>
      body {
        background: lightgray;
        margin:0px;
        padding:0px;
      }
    </style>
    <script language="javascript" type="text/javascript" src="XoaxAjaxGetPhpImage.js"></script>
  </head>
  <body>
    <img id="idLogo"/>
  </body>
</html>

XoaxAjaxGetPhpImage.js

var qHttpRequest = new XMLHttpRequest();
qHttpRequest.open( "GET", "XoaXLogo.php", true );
qHttpRequest.responseType = "arraybuffer";

qHttpRequest.onload = function( e ) {
    var uiaBytes = new Uint8Array( this.response );
    var qBlob = new Blob([uiaBytes], {type:"image/png"});
    var qImageUrl = URL.createObjectURL(qBlob);
    var qImageElement = document.querySelector("#idLogo");
    qImageElement.src = qImageUrl;
};

qHttpRequest.send();

XoaXLogo.php

<?php

$sText = 'XoaX.net';
$sFontFile = './arial.ttf';
$dFontSize = 50;
$iPadding = 20;
$dRotation = 0;

$qBounds = ImageTTFBBox($dFontSize, $dRotation, $sFontFile, $sText);

$iTextWidth = abs($qBounds[2]-$qBounds[6]);
$iTextHeight = abs($qBounds[1]-$qBounds[5]);
$iDigitBoxWidth = $iTextWidth + 2*($iPadding) + 1;
$iDigitBoxHeight = $iTextHeight + 2*($iPadding) + 1;

$dX = ($iDigitBoxWidth / 2) - (($iTextWidth) / 2);
$dY = ($iDigitBoxHeight / 2) + (($iTextHeight) / 2);

$qImage=ImageCreateTrueColor($iDigitBoxWidth,$iDigitBoxHeight);

$qBkgdColor = ImageColorAllocate($qImage,0,0,0);
$qFrgdColor = ImageColorAllocate($qImage,255,0,0);

ImageTTFText($qImage, $dFontSize, $dRotation, $dX, $dY, $qFrgdColor, $sFontFile, $sText);

Header('Content-Type: image/png');
ImagePNG($qImage);
DestroyImage($qImage);

?>
 
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.