【问题标题】:Manipulating an image in PHP results in striped pattern在 PHP 中处理图像会导致条纹图案
【发布时间】:2023-03-21 00:56:01
【问题描述】:

编辑:刚结束使用 Image Magick 并修复了它。

长话短说,我正在尝试使用 PHP 和 jQuery 的组合从 Wikipedia 中提取有关一系列学校的一些基本信息。部分信息是学校的标志或标志,很容易在元素列表中找到。

问题在于尝试在 PHP 中对图像进行一些调整。我知道图像存在于目标 URL(位于不同的域中,如果有帮助的话)并且它是我想要的,但某些图像看起来像这样:

这是原图:

所有文件类型中的其他文件都非常好。

该部分的代码如下:

$ext = end(explode('.', $image));

if($ext == 'png') {
    $img = imagecreatefrompng($image);
}
else if($ext == 'jpeg' || $ext == 'jpg') {
    $img = imagecreatefromjpeg($image);
}
else if($ext == 'gif') {
    $img = imagecreatefromgif($image);
}
else $img = false;

if($img) {
    $raw_x = imagesx($img);
    $raw_y = imagesy($img);

    if($raw_x > $raw_y && $raw_x > 500)
    {
        $y = (500 / $raw_x) * $raw_y;
        $tmp_img = imagecreatetruecolor(500, $y);
        $white = imagecolorallocate($tmp_img, 255, 255, 255);
        imagefill($tmp_img, 0, 0, $white);
        imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, 500, $y, $raw_x, $raw_y);
        $img = $tmp_img;
    }
    else if($raw_y > 500)
    {
        $x = (500 / $raw_y) * $raw_x;
        $tmp_img = imagecreatetruecolor($x, 500);
        $white = imagecolorallocate($tmp_img, 255, 255, 255);
        imagefill($tmp_img, 0, 0, $white);
        imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $x, 500, $raw_x, $raw_y);
        $img = $tmp_img;
    }

    if(!file_exists("../images/schools/" . $id)) mkdir("../images/schools/" . $id, 0755, true);
    imagejpeg($img, "../images/schools/" . $id . "/photo.jpg", 100);
}

我已经在这几天了,我不知道出了什么问题,我希望有一双全新的眼睛能够看到我看不到的东西

【问题讨论】:

  • 变形后的图片都是同一种文件类型吗?
  • imagecopyresampled 期间不缩放它看起来是否正确?
  • image magick 和选项吗?我想这只是评论,但我总是有更好的运气 execing 在我的脚本中调用 Image Magick 而不是尝试使用 php 函数。
  • 您可能对图像的 Alpha 层有问题。你检查过这个页面上的 cmets 吗? php.net/manual/en/function.imagecreatefrompng.php
  • @chiliNUT - Image Magick 工作顺利,非常感谢!

标签: php image


【解决方案1】:

我的猜测是您围绕原始图像大小的条件逻辑正在给您带来问题。您没有处理图像宽度和高度相等的情况,并且您没有处理图像小于 500 像素的情况(不确定这是否是故意的,但如果您指定特定的高度可能会导致 HTML 布局出现问题/ img 元素的宽度)。您应该先进行所有数学运算以计算预期的缩放图像大小,然后在一个地方(而不是在 if 条件下)进行图像创建/调整大小。

我假设您希望始终将图像缩放为高度为 500 像素(如果图像是纵向)或宽度为 500 像素(如果图像是横向)。您将按如下方式计算预期尺寸:

$target_width = 500;
$target_height = 500;

if($raw_x >= $raw_y) { // set scaling factor based on x dimension
   $scaling_factor = 500.0 / $raw_x;
   $target_height = intval(500 * $scaling_factor);
} else { // set scaling factor based on y dimension
   $scaling_factor = 500.0 / $raw_y;
   $target_width = intval(500 * $scaling_factor)
}

然后只有一个代码块用于设置新的临时图像并调整原始图像的大小:

$tmp_img = imagecreatetruecolor($target_width, $target_height);
$white = imagecolorallocate($tmp_img, 255, 255, 255);
imagefill($tmp_img, 0, 0, $white);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $target_width, $target_height, $raw_x, $raw_y);
$img = $tmp_img;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多