php GD add padding to image

∥☆過路亽.° 提交于 2019-12-03 05:48:33
  1. Open the original image
  2. Create a new blank image.
  3. Fill the new image with the background colour your want
  4. Use ImageCopyResampled to resize&copy the original image centered onto the new image
  5. Save the new image

Instead of your switch statement you can also use

$img = imagecreatefromstring( file_get_contents ("path/to/image") );

This will auto detect the image type (if the imagetype is supported by your install)

Updated with code sample

$orig_filename = 'c:\temp\380x253.jpg';
$new_filename = 'c:\temp\test.jpg';

list($orig_w, $orig_h) = getimagesize($orig_filename);

$orig_img = imagecreatefromstring(file_get_contents($orig_filename));

$output_w = 200;
$output_h = 200;

// determine scale based on the longest edge
if ($orig_h > $orig_w) {
    $scale = $output_h/$orig_h;
} else {
    $scale = $output_w/$orig_w;
}

    // calc new image dimensions
$new_w =  $orig_w * $scale;
$new_h =  $orig_h * $scale;

echo "Scale: $scale<br />";
echo "New W: $new_w<br />";
echo "New H: $new_h<br />";

// determine offset coords so that new image is centered
$offest_x = ($output_w - $new_w) / 2;
$offest_y = ($output_h - $new_h) / 2;

    // create new image and fill with background colour
$new_img = imagecreatetruecolor($output_w, $output_h);
$bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red
imagefill($new_img, 0, 0, $bgcolor); // fill background colour

    // copy and resize original image into center of new image
imagecopyresampled($new_img, $orig_img, $offest_x, $offest_y, 0, 0, $new_w, $new_h, $orig_w, $orig_h);

    //save it
imagejpeg($new_img, $new_filename, 80);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!