如何使用 imagescale 并保留边缘外观 "pixels"

How to use imagescale and retain appearance of edge "pixels"

所以我使用 imagecreate 得到了一个 3x3 像素的图像。我想用 imagescale 放大图像,同时保持 "pixels" 的 3x3 网格的外观。但是,右侧和底部边缘的像素大小不同。

这是我的代码和输出图像:

<?php

$image = imagecreate(3, 3);
imagecolorallocate($image, 0, 0, 255);
$red = imagecolorallocate($image, 255, 0, 0);
imagesetpixel($image, 0, 0, $red);
imagesetpixel($image, 1, 1, $red);
imagesetpixel($image, 2, 2, $red);

imagepng(imagescale($image, 200, 200, IMG_NEAREST_NEIGHBOUR));

header("Content-Type: image/png");

这是我的输出:

注意右下角的像素是如何被截掉的。我一直在玩弄新尺寸的数字,最终得到 256x256,此时所有像素的大小都相同。

这是使用 256x256 后的输出:

我的问题是:如何导出具有我描述的效果的调整后图像的尺寸?

奖金问题:是否有一种替代方法可以让我调整到任意大小并保持像素大小大致相同?

我会使用 imagecopyresampled 来实现这一点。

http://php.net/manual/en/function.imagecopyresampled.php

<?php
    $width = 3;
    $height = 3;
    $image = imagecreate($width, $height);
    imagecolorallocate($image, 0, 0, 255);
    $red = imagecolorallocate($image, 255, 0, 0);
    imagesetpixel($image, 0, 0, $red);
    imagesetpixel($image, 1, 1, $red);
    imagesetpixel($image, 2, 2, $red);

    $new_width = 200;
    $new_height = 200;
    $dst = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($dst, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagepng($dst);

    header("Content-Type: image/png");