简体   繁体   English

使用PHP(GD)进行图像裁剪

[英]Image cropping with PHP (GD)

I have the below image which I'd like to crop, so all the black areas are removed and the thumb returned. 我有下面的图像,我想裁剪,所以所有黑色区域被删除,拇指返回。 The thumb must be 130px (width) by 155px (height). 拇指必须是130px(宽度)乘155px(高度)。

拇指

How can I crop it using PHP's GD library? 如何使用PHP的GD库裁剪它? (Imagick library isn't an option). (Imagick库不是一个选项)。

If there is something I can improve in my question, please let me know. 如果我的问题可以改进,请告诉我。

EDIT 编辑

I've used imagecopyresized() function as suggested by @Martijn, with the following code 我使用了@Martijn建议的imagecopyresized()函数,代码如下

imagecopyresized(
    imagecreatetruecolor(130,155) , 
    imagecreatefromjpeg($src_image) , 
    0, 
    0, 
    0, 
    0, 
    130,  
    155,  
    260 , 
    310   
)

What i'm getting is this result 我得到的是这个结果

的Thumb2

What am I doing wrong? 我究竟做错了什么?

This can be hard to do for a library, as the black may differ in size, and the part of the image you may want is not always the same. 对于库来说这很难做到,因为黑色的大小可能不同,并且您可能想要的图像部分并不总是相同。

I suggest jCrop (yes, the site is very minimal), which allows you to select a part of the image. 我建议使用jCrop (是的,网站非常小),它允许您选择图像的一部分。 If it can be done by hand, this is a very easy method. 如果可以手工完成,这是一种非常简单的方法。 I use this in my company CMS', our customers never need explanation on how it works, very natural :) 我在我的公司CMS'中使用它,我们的客户从不需要解释是如何工作的,非常自然 :)


If that is not an option, you can try imagecopyresampled() : 如果这不是一个选项,您可以尝试imagecopyresampled()

imagecopyresampled(
    $dst_image , // the thumb you want to place it on
    $src_image , // the image to crop it from
    0, // place left of thumb
    0, // place top of thumb
    0, // start from left of input image
    0, // start from top of input image
    130,  // destination width
    155,  // destination height
    $src_w , // the width of the image without the black
    $src_h   // the height of the image without the black
)

If you dont have a fixed size for the image on the black canvas, you could write a function to find the offset. 如果黑色画布上的图像没有固定大小,则可以编写一个函数来查找偏移量。 You can do this by taking the first line of pixels, and find the first black pixel, and check if there are (lets say) 10min black pixels after that. 你可以通过拍摄第一行像素来找到第一个黑色像素,并检查之后是否存在(比方说)10分黑色像素。
This can be sensative, you can increase the scouting area to test if the black is also in the lines below. 这可能是敏感的,您可以增加侦察区域来测试黑色是否也在下面的行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM