【问题标题】:Resize PNGs with php Imagick preserving background使用 php Imagick 保留背景调整 PNG 的大小
【发布时间】:2013-06-25 11:51:10
【问题描述】:

我正在尝试使用 cropThumbnailImage 调整图像大小。我使用cropThumbnailImage,因为它调整为原始图像的较短长度,并在两侧均等地裁剪较长边的图像,以便图像的中心部分保持未裁剪。这适用于 jpg 图像,但对于 png 图像,调整大小的 png 会得到黑色背景。

以下是我使用的代码。

    $image = new \Imagick($src);

    // resize & crop
    $image->cropThumbnailImage($width, $height);

    // save new resized file
    $image->writeImage($dest);

为以下 png 图像运行此代码。

http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png http://www.cs.csubak.edu/~mcabrera/CS211/transparent.png http://www.tcarms.com/media/assets/productPhotos/006_G2%20Contender/png/Pistol_12in_Ribbed_Blued_2720.png

根据需要调整输出图像的大小,但 png 图像变为黑色背景。

尝试从here添加以下行,但没有奏效。

imagealphablending( $image, false );
imagesavealpha( $image, true );

网络上还有其他实现 png 图像大小调整的解决方案,但我没有找到像 cropThumbnailImage 那样调整图像大小的解决方案。

【问题讨论】:

  • Aaa 你到底期待什么? JPEG 没有透明度。
  • 谷歌更难?我刚刚进行了谷歌搜索,并在第一次尝试时得到了一些有用的结果。还要检查您的版本号。正如 Carsten 所说,您正在使用 PNG 图像的 JPEG 压缩。 JPEG 不支持透明度。
  • JPG 不透明...请参考 PNG 和 Gif 文件...
  • 您的代码:COMPRESSION_JPEG - JPEG 不是 PNG,它没有透明度。使用此代码,您可以将 PNG 转换为 JPEG。如果你想有透明度,你必须维护扩展......
  • 感谢大家指出压缩。我将其删除并进行了测试。图像似乎仍然是黑色背景。

标签: php image imagick


【解决方案1】:

使用以下 sn-p 保持透明度:

$im = new Imagick($imgPath);
$im->setImageFormat('png');
$im->writeImage('/files/thumbnails/new_title.png');

【讨论】:

    【解决方案2】:
    1. 您的 JPG 不透明...JPG 不是透明图像...此处需要 PNG 和 GIF。

    2. 如果您指的是 PNG,有一个 PHP 代码可以帮助您调整具有透明度的 PNG:

    $x = "坐标 - X 表示作物";

    $y = "坐标 - y 表示作物";

    $w = "宽度";

    $h = "身高";

    $img = imagecreatefrompng($img_path);

    imagealphablending($img, true);

    $img_cropped = imagecreatetruecolor($w, $h);

    imagesavealpha($img_cropped, true);

    imagealphablending($img_cropped, false);

    $transparent = imagecolorallocatealpha($img_cropped, 0, 0, 0, 127);

    imagefill($img_cropped, 0, 0, $transparent);

    imagecopyresampled($img_cropped, $img, 0, 0, $x, $y, $w, $h, $w, $h); // 这里也可以使用 imagecopy()

    imagepng($img_cropped, "your_image_cropped.png", 2);

    imagedestroy($img);

    imagedestroy($img_cropped);

    编辑:试试这个:

    $image = imagecreatefrompng ($filename);

    $new_image = imagecreatetruecolor ( $width, $height ); // 新的高度和高度

    imagealphablending($new_image , false);

    imagesavealpha($new_image , true);

    imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );

    $image = $new_image;

    // 保存

    imagealphablending($image, false);

    imagesavealpha($image, true);

    imagepng ( $image, $filename );

    别忘了定义 $filename, $width, $height!!!!

    【讨论】:

    • 问题询问如何使用 Imagick 调整 png 的大小,而不是 GD 库。
    • 这将导致在调整具有半透明像素的图像大小时出现灰色边框
    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    相关资源
    最近更新 更多