在PHP/Javascript中创建图像,给出图像周围的灰色输出


Image creating in PHP/Javascript giving a grey output around the image

这里是链接,可以访问,看看我是什么意思

演示:

http://img01.fr/test4/

如果我尝试裁剪图像太小,它会输出正确的大小和正确的图像,但是你可以看到周围都是灰色的。

我不知道该怎么改,这是javascript中调用的save.php'

<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
    // image name
    $name = sha1(uniqid(mt_rand(), true));
    // location to save cropped image
    $url = 'temp/'.$name.'.jpg';
    $dst_x = 0;
    $dst_y = 0;
    $src_x = $_POST['x']; // crop Start x
    $src_y = $_POST['y']; // crop Srart y
    $src_w = $_POST['w']; // $src_x + $dst_w
    $src_h = $_POST['h']; // $src_y + $dst_h
    // set a specific size for the image
    // the default is to grab the width and height from the cropped imagee.
    $dst_w = 240;
    $dst_h = 240;
    // remove the base64 part
    $base64 = $_POST['image'];
    // if URL is a base64 string
    if (substr($base64, 0, 5) == 'data:') {
        // remove data from image
        $base64 = preg_replace('#^data:image/[^;]+;base64,#', '', $base64);
        $base64 = base64_decode($base64);
        // create image from string
        $source = imagecreatefromstring($base64);
    }
    else {
        // strip parameters from URL
        $base64 = strtok($base64, '?');
        list($height, $width, $type) = getimagesize($base64);
        // create image
        if ($type == 1)
            $source = imagecreatefromgif($base64);
        else if ($type == 2)
            $source = imagecreatefromjpeg($base64);
        else if ($type == 3) {
            $source = imagecreatefrompng($base64);
        // keep transparent background
        //imagealphablending($image, FALSE);
        //imagesavealpha($image, TRUE);
    }
    else die();
    }
    $image = imagecreatetruecolor($dst_w, $dst_h);
    imagecopyresampled($image, $source, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    $white = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $white);
    // save image
    imagejpeg($image, $url, 100);
    // return URL
    $validation = array (
        'url'     => $url
    );
    echo json_encode($validation);
}

我希望它周围只有白色,而不是这个灰色的东西。

您需要在复制重新采样之前填充图像:

$image = imagecreatetruecolor($dst_w, $dst_h);
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
imagecopyresampled($image, $source, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

我还看到JavaScript正在传递无效的x、y、w和h参数,然后PHP脚本使用这些参数来调整图像的大小。例如,我尝试了这个页面,发送了以下POST参数:

<>之前-297.61904761904765 x = y = -297.61904761904765易名= 595.2380952380953 h = 595.2380952380953之前

因为输入图像只有250×500, 595对于$src_w$src_h都太大。负数也没有意义。