我目前正在使用GD php库来缩放一些图像信箱样式,并用黑色填充生成的空白区域。但是,我需要使用我在另一个图像文件中的模式填充空白区域。关于如何做到这一点的任何想法?
这是我用来缩放图像的代码:
function resize_image($source_image, $destination_width, $destination_height, $type = 0) {
// $type (1=crop to fit, 2=letterbox)
$source_width = imagesx($source_image);
$source_height = imagesy($source_image);
$source_ratio = $source_width / $source_height;
$destination_ratio = $destination_width / $destination_height;
if ($type == 1) {
// crop to fit
if ($source_ratio > $destination_ratio) {
// source has a wider ratio
$temp_width = (int)($source_height * $destination_ratio);
$temp_height = $source_height;
$source_x = (int)(($source_width - $temp_width) / 2);
$source_y = 0;
} else {
// source has a taller ratio
$temp_width = $source_width;
$temp_height = (int)($source_width / $destination_ratio);
$source_x = 0;
$source_y = (int)(($source_height - $temp_height) / 2);
}
$destination_x = 0;
$destination_y = 0;
$source_width = $temp_width;
$source_height = $temp_height;
$new_destination_width = $destination_width;
$new_destination_height = $destination_height;
} else {
// letterbox
if ($source_ratio < $destination_ratio) {
// source has a taller ratio
$temp_width = (int)($destination_height * $source_ratio);
$temp_height = $destination_height;
$destination_x = (int)(($destination_width - $temp_width) / 2);
$destination_y = 0;
} else {
// source has a wider ratio
$temp_width = $destination_width;
$temp_height = (int)($destination_width / $source_ratio);
$destination_x = 0;
$destination_y = (int)(($destination_height - $temp_height) / 2);
}
$source_x = 0;
$source_y = 0;
$new_destination_width = $temp_width;
$new_destination_height = $temp_height;
}
$destination_image = imagecreatetruecolor($destination_width, $destination_height);
if ($type > 1) {
imagefill($destination_image, 0, 0, imagecolorallocate($destination_image, 0, 0, 0));
}
imagecopyresampled($destination_image, $source_image, $destination_x, $destination_y, $source_x, $source_y, $new_destination_width, $new_destination_height, $source_width, $source_height);
return $destination_image;
}
谢谢
编辑------------------
我现在正在使用这个完美运行的代码,使用下面建议的方法:
$destination_image = imagecreatetruecolor($destination_width, $destination_height);
if ($type > 1) {
if ($pattern != NULL) {
$pattern = imagecreatefrompng($pattern);
imagesettile($destination_image, $pattern);
imagefill($destination_image, 0, 0, IMG_COLOR_TILED);
} else {
imagefill($destination_image, 0, 0, imagecolorallocate($destination_image, 0, 0, 0));
}
}
imagecopyresampled($destination_image, $source_image, $destination_x, $destination_y, $source_x, $source_y, $new_destination_width, $new_destination_height, $source_width, $source_height);
return $destination_image;
$ pattern是背景图片的文件路径,用于填充信箱!
答案 0 :(得分:0)
首先使用imagesettile()准备背景以创建平铺的画布以覆盖您的信箱,然后使用{{3的source_x / y / w / h参数将图像的信箱部分复制到此资源中}或imagecopy()。