php create image and add background image to it

RussellHarrower picture RussellHarrower · Jul 13, 2012 · Viewed 8.2k times · Source

I would like to add an image as the background image to the image that is created by my PHP code

<?php
header('Content-type: image/gif');
// Fetch GET params
$mode = isset($_GET["mode"]) ? strip_tags($_GET["mode"]) : "big";
$url = isset($_GET["text"]) ? $_GET["text"] : "This is an Invalid Code";

// Get size depending on mode
$size = ($mode && $mode == "small") ? "36" : "200";
// Get chart data. Limit data length if mode is small
$chl = ($mode && $mode == "small") ? substr($url, 0, 33) : $url;
// Assemble chart image URL
$imgUrl = "http://chart.apis.google.com/chart?chs=" . $size . "x" . $size . "&cht=qr&chld=H|0&chl=" . $chl;

// Load, transform and write transparent QR code image
$im = imagecreatefrompng($imgUrl);
imagetruecolortopalette($im, false, 2);
$white = imagecolorclosest($im, 0, 0, 0);
imagecolortransparent($im, $white);
imagegif($im);
imagedestroy($im);
?>

The image is located on the same server

http://www.example.com/img/sitebg.png

What I have tried

<?php
header('Content-type: image/gif');
// Fetch GET params
$mode = isset($_GET["mode"]) ? strip_tags($_GET["mode"]) : "big";
$url = isset($_GET["text"]) ? $_GET["text"] : "This is an Invalid Code";

// Get size depending on mode
$size = ($mode && $mode == "small") ? "36" : "200";
// Get chart data. Limit data length if mode is small
$chl = ($mode && $mode == "small") ? substr($url, 0, 33) : $url;
// Assemble chart image URL
$imgUrl = "http://chart.apis.google.com/chart?chs=" . $size . "x" . $size . "&cht=qr&chld=H|0&chl=" . $chl;

// Load, transform and write transparent QR code image
$im2 = imagecreatefrompng("http://www.example.com/example/img/BG.png");
$im = imagecreatefrompng($imgUrl);
imagetruecolortopalette($im, false, 2);
$white = imagecolorclosest($im, 0, 0, 0);
imagecolortransparent($im, $white);

// Merge the stamp onto our photo with an opacity (transparency) of 50%
imagecopymerge($im, $im2);

// Save the image to file and free memory
imagepng($im);
//imagegif($im);
imagedestroy($im);
?>

Answer

Sven van Zoelen picture Sven van Zoelen · Jul 13, 2012

You want to draw the graph over the bg image right?

Then just start bij creating the image object from the background image, then merge it with the graph using the command imagecopymerge().

  1. create image object with the bg image
  2. create png graph as new image object
  3. merge them together
  4. show

Here is a example how to use it: click!