douren6874 2010-07-17 16:37

# 问题使用GD库将图像裁剪为完美的正方形

I use a class that automatically crops an image as a square based on some options. The problem is that when the image is of a certain width and height, the image is cropped but a 1px column of black pixels is added to the right of the image. I think that the problem is in the mathematics used to generate the new image size... Maybe when the division of the height and the width gives a decimal number then the square is not perfect and the black pixels are added...

Any solution?

This is how I call the object:

``````\$resizeObj = new resize(\$image_file); // *** 1) Initialise / load image
\$resizeObj -> resizeImage(182, 182, 'crop'); // *** 2) Resize image
\$resizeObj -> saveImage(\$destination_path, 92); // *** 3) Save image
``````

The part of the class I'm talking about:

``````private function getOptimalCrop(\$newWidth, \$newHeight)
{

\$heightRatio = \$this->height / \$newHeight;
\$widthRatio  = \$this->width /  \$newWidth;

if (\$heightRatio < \$widthRatio) {
\$optimalRatio = \$heightRatio;
} else {
\$optimalRatio = \$widthRatio;
}

\$optimalHeight = \$this->height / \$optimalRatio;
\$optimalWidth  = \$this->width  / \$optimalRatio;

return array('optimalWidth' => \$optimalWidth, 'optimalHeight' => \$optimalHeight);
}

private function crop(\$optimalWidth, \$optimalHeight, \$newWidth, \$newHeight)
{
// *** Find center - this will be used for the crop
\$cropStartX = ( \$optimalWidth / 2) - ( \$newWidth /2 );
\$cropStartY = 0; // start crop from top

\$crop = \$this->imageResized;
//imagedestroy(\$this->imageResized);

// *** Now crop from center to exact requested size
\$this->imageResized = imagecreatetruecolor(\$newWidth , \$newHeight);
imagecopyresampled(\$this->imageResized, \$crop , 0, 0, \$cropStartX, \$cropStartY, \$newWidth, \$newHeight , \$newWidth, \$newHeight);
}
``````

Update:

Maybe changing this:

``````\$heightRatio = \$this->height / \$newHeight;
\$widthRatio  = \$this->width /  \$newWidth;
``````

with this:

``````\$heightRatio = round(\$this->height / \$newHeight);
\$widthRatio  = round(\$this->width /  \$newWidth);
``````
• 写回答

#### 1条回答默认 最新

• duandu2980 2010-07-17 16:43
关注

This line:

``````\$cropStartX = ( \$optimalWidth / 2) - ( \$newWidth /2 );
``````

looks suspicious.

If this is integer division then for images that are an odd number of pixels wide you'll get truncation. Try:

``````\$cropStartX = ( \$optimalWidth / 2.0) - ( \$newWidth / 2.0 );
``````

Make sure that all your arithmetic is using real numbers, preferably double precision ones, but with numbers in the range you are dealing with it should be OK to work in single precision floats.

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥50 微信聊天记录备份到电脑提示成功了，但还是没同步到电脑微信
• ¥15 python怎么在已有视频文件后添加新帧
• ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
• ¥15 fluent里模拟降膜反应的UDF编写
• ¥15 MYSQL 多表拼接link
• ¥15 关于某款2.13寸墨水屏的问题
• ¥15 obsidian的中文层级自动编号
• ¥15 同一个网口一个电脑连接有网，另一个电脑连接没网
• ¥15 神经网络模型一直不能上GPU
• ¥20 wpf datagrid单元闪烁效果失灵