2017-08-27 83 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