PHP 图像裁剪制作黑色图像

PHP image crop making black images

这段代码有问题。该代码是一个 PHP 页面,用于接收有关裁剪图像位置的信息。发送的信息似乎没问题,是坐标(x1, y1, x2, y2),但是PHP代码结果只是生成了一个黑色图像。虽然,至少是合适的尺度。

我对 php 很陌生,很抱歉,如果这是基本问题,但我就是找不到答案:/

图像裁剪php:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $targ_w = $_POST['w'];
    $targ_h = $_POST['h'];
    $jpeg_quality = 90;

    $src = $_POST['img_file'];
    $img_r = imagecreatefromjpeg($src);
    $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

    imagecopyresampled($dst_r,$img_r,0,0,$_POST['x1'],$_POST['y1'],
    $targ_w,$targ_h,$_POST['w'],$_POST['h']);

    header('Content-type: image/jpeg');
    imagejpeg($dst_r,$src,$jpeg_quality);

    exit;
}
elseif($_SERVER['REQUEST_METHOD'] == 'GET'){
    $src_g = './demo2/pics/' . $_GET['id'] . 'v' . $_GET['v'] . '.jpg';
    if(!file_exists($src_g)){
        die();
    }
}
?>

正如我在评论中所说,您必须将 enctype 设置为 multipart/form-data 以便您的表单支持文件上传。这是一个工作表单的示例:

<form method="POST" enctype="multipart/form-data">
  <input type="file" name="file" id="file" />
  <input type="text" name="x1" value="0" />
  <input type="text" name="y1" value="0" />
  <input type="submit" value="Upload" />
</form>

然后检查是否设置了$_FILES数组,然后修改图片输出到浏览器:

// enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', true);

if($_SERVER['REQUEST_METHOD'] == 'POST' && 
   isset($_FILES['file']) && 
   $_FILES['file']['error'] == 0) {

   // create an image resource from the temporary file
   $src = imagecreatefromjpeg($_FILES['file']['tmp_name']);
   // get dimensions of the source image
   $src_w = imagesx($src);
   $src_h = imagesy($src);

   // get offset to copy from 
   $src_x = intval($_POST['x1']);
   $src_y = intval($_POST['y1']);
   $dst_w = $src_w - $src_x;
   $dst_h = $src_h - $src_y;

   // create destination image 
   $dst = imagecreatetruecolor($dst_w, $dst_h);

   // copy the original image based on offset to destination
   // notice that we subtract the offset from the source width and hight
   // so we use `$dst_w` && `$dst_h`
   imagecopyresampled($dst, 
                      $src, 0, 0, 
                      $src_x, $src_y, 
                      $dst_w, $dst_h, 
                      $dst_w, $dst_h);
   // destroy resource
   imagedestroy($src);

   // output the image to the browser
   header('Content-type: image/jpeg');
   imagejpeg($dst);
   imagedestroy($dst);
   exit;
}

请注意,这只是一个简单示例,您应该检查错误等。就像我在评论中所说的那样,始终启用 error_reporting 这通常会为您提供有关问题所在的信息。要记住的另一件事是,上面的代码假定上传文件确实是一个 .jpg 文件,这也是您可能需要首先验证的文件。

正如您在评论中所问的那样,您当然可以从表单中发送文件位置。那么你将不得不稍微修改一下代码:

if(isset($_POST['file_path']) && file_exists($_POST['file_path'])) {
   $src = $_POST['img_path'];
   $img_r = imagecreatefromjpeg($src);

参考

POST method uploads in PHP