php imagecopyresampled 问题

标签 php gd

我在使用 imagecopyresampled 时遇到一些问题,主要是图像未正确缩放、图像位置错误以及边缘周围有黑色边框。

我设置了以下变量

    $tW = $width; // Original width of image
    $tH = $height; // Orignal height of image

    $w = postvar; // New width
    $h = postvar; // New height
    $x = postvar; // New X pos
    $y = postvar; // New Y pos

然后运行以下命令

    $tn = imagecreatetruecolor($w, $h);
    $image = imagecreatefromjpeg('filepathhere.jpeg');
    imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH);

如果有人有任何线索,那将是很大的帮助!谢谢

最佳答案

这里有几个问题。首先,您不应该创建具有指定的新高度和宽度的新图像,而是根据原始图像的比例计算它们应该是什么,否则缩放后的图像将失真。例如,下面的代码将创建一个适当调整大小的图像,该图像将适合给定的 $w x $h 矩形:

$tW = $width;    //original width
$tH = $height;   //original height

$w = postvar;
$h = postvar;

if($w == 0 || $h == 0) {
    //error...
    exit;
}

if($tW / $tH > $w / $h) {
    // specified height is too big for the specified width
    $h = $w * $tH / $tW;
}
elseif($tW / $tH < $w / $h) {
    // specified width is too big for the specified height
    $w = $h * $tW / $tH;
}

$tn = imagecreatetruecolor($w, $h);  //this will create it with black background
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255));    //fill it with white;

//now you can copy the original image:
$image = imagecreatefromjpeg('filepathhere.jpeg');
//next line will just create a scaled-down image
imagecopyresampled($tn, $image, 0, 0, 0, 0, $w, $h, $tW, $tH);

现在,如果您只想复制原始图像的特定部分,例如从坐标 ($x, $y) 到右上角,那么您需要将其包含到您的计算:

$tW = $width - $x;    //original width
$tH = $height - $y;   //original height

$w = postvar;
$h = postvar;

if($w == 0 || $h == 0) {
    //error...
    exit;
}

if($tW / $tH > $w / $h) {
    // specified height is too big for the specified width
    $h = $w * $tH / $tW;
}
elseif($tW / $tH < $w / h) {
    // specified width is too big for the specified height
    $w = $h * $tW / $tH;
}

$tn = imagecreatetruecolor($w, $h);  //this will create it with black background
imagefill($tn, 0, 0, imagecolorallocate($tn, 255, 255, 255));    //fill it with white;

//now you can copy the original image:
$image = imagecreatefromjpeg('filepathhere.jpeg');
//next line will create a scaled-down portion of the original image from coordinates ($x, $y) to the lower-right corner
imagecopyresampled($tn, $image, 0, 0, $x, $y, $w, $h, $tW, $tH);

如果您提供有关您想要实现的目标的更多详细信息,我也许可以提供进一步的帮助。

关于php imagecopyresampled 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11331288/

相关文章:

javascript - 当子链接处于事件状态时,将事件类添加到父 li

PHP & GD - 透明背景被附近的颜色填充

php 将图像与其在不同位置的翻转和旋转 View 合并

php - php gd中img过滤器亮度函数的值范围

php - 如何在 PHP 的 GD 库中为文本添加光晕或阴影?

PHP 函数和变量以字符串形式存储在数据库中

php - PHP 脚本中的 XSS 漏洞

php - MySQL 返回所有带有空字符串的行作为 where 子句

php - 使用 PHP 检测图像的主要阴影

c# - 使用 C# 和 PHP 更新 mysql