简体   繁体   中英

PHP gd make thumbnail from generated image

I have a php script cakeChart.php which is generating simple cake.

$image = imagecreatetruecolor(100, 100);

$white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);


header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

In file createThumb.php I want to load generated image from cakeChart.php . Something like(I know it is bad):

$pngImage = imagecreatefrompng("pieChart.php");

I want to make thumbnail of this image. Right now the only reference on this php file is this

<a href="pieChart.php" target="blank">PHP pie chart</a><br>

but I want to replace this text with tumb, whitch will be generated in createThumb.php . Is it possible to make image with cakeChart.php and then convert it to thumbnail with createThumb.php ?

You would need another script that called cakeChart.php and resized it, like so:

<?php
$src = imagecreatefrompng('http://example.com/cakeChart.php');

$width = imagesx($src);
$height = imagesy($src);
// resize to 50% of original:
$new_width = $width * .5;
$new_height = $height * .5;

$dest = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dest, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

header('Content-type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);

Then your HTML would reference that file as an image source:

<a href="pieChart.php" target="blank">
    <img src="http://example.com/cakeChartThumb.php" alt="PHP pie chart">
</a>

While this will work, it is not an efficient use of server resources. Even a small number of page views might cause the server CPU usage to spike and impact performance. You should really create both files once and save them to disk, referencing them in your HTML as you would any other image file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM