2017-08-27 84 views
-1

我试图从YouTube JPEG缩略图的顶部和底部剪切掉×45像素的顶部和底部×45像素,例如this one是480像素X 360像素。如何裁剪从JPEG

它看起来是这样的:在图像的顶部和底部

enter image description here

通知的45像素的黑条。我只是想要删除这些图片,使得生成的图片为480px x 270px,黑色条消失了。

我已通过从this stack post实现示例实现部分成功。这是基于我的PHP功能上:

function CropImage($sourceImagePath, $width, $height){ 
    $src = imagecreatefromjpeg($sourceImagePath); 
    $dest = imagecreatetruecolor($width, $height); 
    imagecopy($dest, $src, 0, 0, 20, 13, $width, $height); 
    header('Content-Type: image/jpeg'); 
    imagejpeg($dest); 
    imagedestroy($dest); 
    imagedestroy($src); 
} 

并号召正是如此:

CropImage("LOTR.jpg", 480, 270); 

一些种植的发生,但2个问题导致:

  1. 它不裁剪顶部和底部,而它似乎裁剪左侧和底部,造成这样的:

enter image description here

  1. 从我使用的PHP代码片段中看不到如何生成新文件。相反,我在浏览器中执行的PHP脚本只是在浏览器中呈现变形的文件。我不希望这样的事情发生,我希望能够通过一个DEST路径进入功能,并把它创建新的文件(而不是送什么东西给客户端/浏览器)去掉顶部×45像素和底部×45像素。很显然,header('Content-Type: image/jpeg');是问题的一部分,但删除仍然不会给我一个目标文件写入服务器,methinks。

我也在找PHP docs here。看起来改变imagecopy($dest, $src, 0, 0, 20, 13, $width, $height);中的参数可以解决这个问题,但是我不清楚这些参数应该是什么。 resulting thumbnails inside the YouTube tab look odd与黑条。提前感谢您的任何建议。

+0

[imagecopy](http://php.net/manual/en/function.imagecopy.php)[imagejpeg](http://php.net/manual/en/function.imagejpeg.php) – tkausl

+0

我传递给'imagejpeg()'什么? '$ src'? '$ dest'?还有别的吗? – HerrimanCoder

+1

两者。你只需要改变'$ src_x'和'$ src_y',20和13是错误的。 – tkausl

回答

1
<?php 
function CropImage($sourceImagePath, $width, $height){ 

    // Figure out the size of the source image 
    $imageSize = getimagesize($sourceImagePath); 
    $imageWidth = $imageSize[0]; 
    $imageHeight = $imageSize[1]; 

    // If the source image is already smaller than the crop request, return (do nothing) 
    if ($imageWidth < $width || $imageHeight < $height) return; 

    // Get the adjustment by dividing the difference by two 
    $adjustedWidth = ($imageWidth - $width)/2; 
    $adjustedHeight = ($imageHeight - $height)/2; 

    $src = imagecreatefromjpeg($sourceImagePath); 

    // Create the new image 
    $dest = imagecreatetruecolor($width,$height);  

    // Copy, using the adjustment to crop the source image 
    imagecopy($dest, $src, 0, 0, $adjustedWidth, $adjustedHeight, $width, $height); 

    imagejpeg($dest,'somefile.jpg'); 
    imagedestroy($dest); 
    imagedestroy($src); 
} 
+0

user2182349你的解决方案完美的工作除了我仍然看不到如何将修改后的图像保存到服务器。 'header('Content-Type:image/jpeg');'当然需要删除,但保存更改后的图像的语法是什么? – HerrimanCoder

+0

Imagejpeg($ dest,'somefile.jpg'); – user2182349

+0

是的,就是这样。请更新您的答案,并删除'header'。所以我可以接受,也可以帮助别人。 – HerrimanCoder