hello -
I've been trying to return an image straight to the browser. The idea is to return a PNG when the URL is called, e.g domain.com/image
I've borrowed some code from the web and whereas outside of MODx the following works, as a snippet it doesn't return anything. I just see a small image log in the browser.
It seems you cant return $image or write to the browser imagepng($image); with or without ob_start();. It must be Revo's parsing process getting involved but I'm not smart enough to figure it out.
I've setup my test site with a PNG content type for the url (eg. domain.com/image).
I'm sure I could return an image referenced within an <img> but I want to be able to pull the image in to other sites as an image.
I've also tried
https://forums.modx.com/index.php?topic=67177.0 but with no luck.
Any ideas appreciated
<?php
// PHP placeholder images
// Version: 0.1
// Author: Hinerangi Courtenay - @sky_maiden
// Usage (all parameters are optional):
// <img src="placeholder.php?size=400x150&bg=eee&fg=999&text=Generated+image" alt="Placeholder image" />
// Inspired by http://placehold.it/
// Dimensions
$getsize = isset($_GET['size']) ? $_GET['size'] : '100x100';
$dimensions = explode('x', $getsize);
// Create image
$image = imagecreate($dimensions[0], $dimensions[1]);
// Colours
$bg = isset($_GET['bg']) ? $_GET['bg'] : 'ccc';
$bg = hex2rgb($bg);
$setbg = imagecolorallocate($image, $bg['r'], $bg['g'], $bg['b']);
$fg = isset($_GET['fg']) ? $_GET['fg'] : '555';
$fg = hex2rgb($fg);
$setfg = imagecolorallocate($image, $fg['r'], $fg['g'], $fg['b']);
// Text
$text = isset($_GET['text']) ? strip_tags($_GET['text']) : $getsize;
$text = str_replace('+', ' ', $text);
// Text positioning
$fontsize = 4;
$fontwidth = imagefontwidth($fontsize); // width of a character
$fontheight = imagefontheight($fontsize); // height of a character
$length = strlen($text); // number of characters
$textwidth = $length * $fontwidth; // text width
$xpos = (imagesx($image) - $textwidth) / 2;
$ypos = (imagesy($image) - $fontheight) / 2;
//imagealphablending($image, true); // setting alpha blending on
//imagesavealpha($image, true); // save alphablending setting
// Generate text
imagestring($image, $fontsize, $xpos, $ypos, $text, $setfg);
// Render image
ob_start();
imagepng($image);
$output = ob_get_contents();
ob_end_clean();
return $output;
// Convert hex to rgb (modified from csstricks.com)
function hex2rgb($colour)
{
$colour = preg_replace("/[^abcdef0-9]/i", "", $colour);
if (strlen($colour) == 6)
{
list($r, $g, $b) = str_split($colour, 2);
return Array("r" => hexdec($r), "g" => hexdec($g), "b" => hexdec($b));
}
elseif (strlen($colour) == 3)
{
list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
return Array("r" => hexdec($r), "g" => hexdec($g), "b" => hexdec($b));
}
return false;
}
?>