在图像上绘制形状并将其保存在PHP中


Drawing shapes on image and saving it in PHP

我正在尝试从服务器中的某个位置读取图像,然后在上面划线,然后覆盖该位置的图像。

我的代码如下:

function drawShapes($src_path, $json)
{       
    echo "---inside draw Sharpes-------";
    $x1= $json['x1'];
    $y1= $json['y1'];
    $x2= $json['x2'];
    $y2= $json['y2'];
    $x3= $json['x3'];
    $y3= $json['y3'];
    $x4= $json['x4'];
    $y4= $json['y4'];
    $type = exif_imagetype($src_path);
    $allowedTypes = array( 
        1,  // [] gif 
        2,  // [] jpg 
        3,  // [] png 
    ); 
    if (!in_array($type, $allowedTypes)) { 
        return false; 
    } 
    switch ($type) { 
        case 1 : 
            $im = imageCreateFromGif($src_path); 
        break; 
        case 2 :    
            $im = imageCreateFromJpeg($src_path);               
        break; 
        case 3 : 
            $im = imageCreateFromPng($src_path); 
        break; 
    }  
    if (!$im)
        return false;
    imagesetthickness($im, 5);
    $color = imagecolorallocate($im, 255, 255, 255);
    echo $color;
    imageline($im, $x1, $y1, $x2, $y2, $color);
    imageline($im, $x2, $y2, $x3, $y3, $color);
    imageline($im, $x3, $y3, $x4, $y4, $color);
    imageline($im, $x4, $y4, $x1, $y1, $color);
    header("Content-type: image/jpeg");
    imagejpeg($im,$src_path);
    imagedestroy($im);
}

这里$src_path="uploads/case.jpg"-uploads是我的解决方案中的一个文件夹&case.jpg是图像文件名。但我得到了图像丢失的图标作为输出。我做错了什么?

解决方案是什么?非常感谢。

在发送标头之前,您正在回显数据。

如果你想覆盖该位置的图像,然后在浏览器中显示,也许你可以使用这种调整:

<?php
function drawShapes($src_path, $json)
{
    //echo "---inside draw Sharpes-------";
    $x1= $json['x1'];
    $y1= $json['y1'];
    $x2= $json['x2'];
    $y2= $json['y2'];
    $x3= $json['x3'];
    $y3= $json['y3'];
    $x4= $json['x4'];
    $y4= $json['y4'];
    $type = exif_imagetype($src_path);
    $allowedTypes = array(
        1,  // [] gif
        2,  // [] jpg
        3,  // [] png
    );
    if (!in_array($type, $allowedTypes)) {
        return false;
    }
    switch ($type) {
        case 1 :
            $im = imageCreateFromGif($src_path);
            break;
        case 2 :
            $im = imageCreateFromJpeg($src_path);
            break;
        case 3 :
            $im = imageCreateFromPng($src_path);
            break;
    }
    if (!$im)
        return false;
    imagesetthickness($im, 5);
    $color = imagecolorallocate($im, 255, 255, 255);
    //echo $color;
    imageline($im, $x1, $y1, $x2, $y2, $color);
    imageline($im, $x2, $y2, $x3, $y3, $color);
    imageline($im, $x3, $y3, $x4, $y4, $color);
    imageline($im, $x4, $y4, $x1, $y1, $color);
    imagejpeg($im,$src_path);
    imagedestroy($im);
    $fp = fopen($src_path, 'rb');
    header("Content-Type: image/jpeg");
    header("Content-Length: " . filesize($src_path));
    fpassthru($fp);
    exit;
}