2017-02-24 104 views
-1

我需要使用尺寸來裁剪圖像。如何在PHP中用尺寸裁剪圖像(沒有質量損失)?

並將其保存到JPEG格式的本地。

尺寸,我收到的,

{"left":82.5,"top":48.875,"width":660,"height":371.25} 

我需要從圖像的原始大小裁剪。

Ex。圖像是1200x800,然後結果圖像尺寸從實際尺寸,不調整大小或任何。因爲質量應該是一樣的。

我怎樣才能使用這些參數來裁剪圖像?

可能嗎?

+0

這些值是什麼尺寸? 0.5 px將很難生成 – Martin

回答

0

使用內置imagick class

$image = realpath("/path/to/your/image.extension"); 
$cropped = realpath("/path/to/your/output/image.png"); 

$imObj = new Imagick(); 
$imObj->cropImage($width, $height, $offset_x, $offset_y); 
$imObj->setImageFormat("png"); // this is unnesesary, you can force an image format with the extension of the output filename. 
$imObj->writeImage($cropped); 

至於無損輸出,使用具有無損編碼的圖像格式。 PNG是完美的工作,因爲它是專爲網絡傳輸而設計的(因此是「Adam-7」隔行掃描)。 檢查關於平面設計組無損圖像格式此相關的問題:

What are lossless image formats?

+1

Imagick是***沒有內置在這»PECL擴展沒有與PHP捆綁在一起。 ' – Martin

0

可以使用imageCopyResampled功能,設計非常正是這一點。

$image = imagecreatefromjpeg($imageFileURL); 
/*** 
* resize values (imported) 
***/ 
$left = 82; 
$top = 49; 
$width = 660; 
$height = 371; 

/*** 
* Create destination image 
***/ 
$newImage = imagecreatetruecolor($width,$height); 
$saveToFile = "destintion filespace of image file.jpg" 

if(imagecopyresampled($newImage, $image, //dest/source images 
     0, 0,       // dest coordinates 
    $left, $top,       // source coordinates 
    $width, $height,      // size of area to paste to 
    $width, $height      // size of area to copy from 
)){ 
    imagejpeg($newImage,$saveToFile,100); //zero compression saved to file 
    print "image resized ok!!"; 
} 

新fileimage將與$width$height指定的尺寸和將被從由$left$top給出的值的原始圖像的偏移量。從你的問題來看,這看起來像你想要的。這不會調整或更改圖像的壓縮(直到您保存該文件,然後可能自己設置這些細節)。