Voting

: five minus three?
(Example: nine)

The Note You're Voting On

nick at prient dot co dot uk
19 years ago
Task: Rotate a large image, then reduce it in size and place it on a small background (i.e. as an Inset).

Problem: If you resize the image first, the rotation becomes hugely aliased... So, it makes sense to rotate it first, then shrink it.
Unfortunately, when you resample the image, you lose the background color (at least, some of it may change), so you can no longer set transparancy as you require. If instead you resize the image (rather than resample), again, the aliasing looks bad.

Solution: Resize the background - make it bigger. Then add the original (large) inset, and resize the whole thing back to normal.

<?php
/* We will shrink the inset to 25% */
$resizePercentage = 0.25;

/* Load a source image and a background */
$iSource = ImageCreateFromJpeg($source_file);
$iBackground = ImageCreateFromJpeg($background_file);

/* Do something here, such a rotate, skew etc */
...
/* Assume $iSource is still the image we want to insert onto the background */

/* Set the background color to be transparent */
$cBackground = ImageColorClosest($iSource, 255, 0, 255);
ImageColorTransparent($iSource, $cBackground);

/* Resize the background - make it huge */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) / $resizePercentage, ImageSY($iBackground ) / $resizePercentage);
/* Place the image on the background - all full size, so no aliasing issues */
ImageCopyMerge($iBackground , $iSource,
((
ImageSX($iBackground ) - ImageSX($iSource)) / 2),
((
ImageSY($iBackground ) - ImageSY($iSource)) / 2) - 25, 0, 0, ImageSX($iWorking), ImageSY($iSource), 100);
/* Shrink the combined image... no issues with transparancy! */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) * $resizePercentage, ImageSY($iBackground ) * $resizePercentage);

/* Output the image as a PNG */
header("Content-Type: image/png");
ImagePng($iBackground);
exit();

function
ImageResize($pImage, $t_width, $t_height) {
// Target image
$iCanvas = @ImageCreateTrueColor($t_width, $t_height);
// Source dimensions
$s_width = ImageSX($pImage);
$s_height = ImageSY($pImage);
// Copy image
ImageCopyResampled($iCanvas, $pImage, 0, 0, 0, 0, $t_width, $t_height, $s_width, $s_height);
// Return image
return $iCanvas;
}
?>

<< Back to user notes page

To Top