Skip to content

Instantly share code, notes, and snippets.

@vitorvargasdev
Last active December 22, 2019 21:19
Show Gist options
  • Save vitorvargasdev/587a31daf98b3b4c86ee60886921c203 to your computer and use it in GitHub Desktop.
Save vitorvargasdev/587a31daf98b3b4c86ee60886921c203 to your computer and use it in GitHub Desktop.
<?php
function create_image($img_url, $width, $height, $quality)
{
function resize_image($new_width, $new_height, $image, $old_width, $old_height)
{
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
return $new_image;
}
$imageTypeArray = array
(
0 => 'UNKNOWN',
1 => 'GIF',
2 => 'JPEG', /* and JPG */
3 => 'PNG',
4 => 'SWF',
5 => 'PSD',
6 => 'BMP',
7 => 'TIFF_II',
8 => 'TIFF_MM',
9 => 'JPC',
10 => 'JP2',
11 => 'JPX',
12 => 'JB2',
13 => 'SWC',
14 => 'IFF',
15 => 'WBMP',
16 => 'XBM',
17 => 'ICO',
18 => 'COUNT',
);
$filename = file_get_contents($img_url);
$image = imagecreatefromstring($filename);
list($old_width, $old_height, $type) = getimagesize($img_url);
$new_image = resize_image($width, $height, $image, $old_width, $old_height);
ob_start();
// Output the image
switch ($imageTypeArray[$type]) {
case "UNKNOWN":
//
break;
case "JPEG":
imagejpeg($new_image, null, $quality);
break;
case "PNG":
imagepng($new_image, null, 9);
break;
}
$img = ob_get_clean();
ob_end_clean();
$base64 = base64_encode($img);
imagedestroy($image);
imagedestroy($new_image);
return ('data: image' . ';base64,' . $base64);
}
echo "<img src='" . create_image("https://images.pexels.com/photos/326055/pexels-photo-326055.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", 480, 320, 50) . "' />";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment