干预裁剪后的 png 图像周围的黑色边框
Posted
技术标签:
【中文标题】干预裁剪后的 png 图像周围的黑色边框【英文标题】:Intervention black borders around cropped png image 【发布时间】:2018-07-30 21:01:51 【问题描述】:我在 laravel 应用程序中使用Intervention(就像每个人一样)并且遇到了一个问题,即在裁剪图像时会在图像周围应用黑色边框,如下所示:
它保留了图像文件的透明度,然后用黑色填充图像的其余部分,这似乎很奇怪。
我裁剪和保存这些图像的方法如下:
/**
* Accept parameter array (
'_token' => 'E1seBDvsEBj1aNpLmenIKkAoNSKct878tqnIwOQO',
'x' => 55,
'y' => '30',
'width' => '200',
'height' => '200',
'filename' => '1_somerandomhash.jpg',
)
*
* Move the given filename from TMP_ORG_LOGOS to ORGANIZATION_LOGOS_DIRECTORY, apply
* cropped dimensions, rename to organization slug name plus small random hash, return
* true or false
*
* @param array $params
* @return bool
*/
public function saveLogo(int $userId, array $params) : bool
try
$org = $this->userService->getUserDefaultOrg($userId);
$newImageName = $org->slug . '-' . uniqid() . '.png';
Image::make(getenv('TMP_ORG_LOGOS') . $params['filename'])
->crop(round($params['width']), round($params['height']),
round($params['x']), round($params['y']))
->save(getenv('ORGANIZATION_LOGOS_DIRECTORY') . $newImageName, 100);
$org->logo = $newImageName;
$org->save();
return true;
catch (\Exception $e)
return false;
以前有人遇到过这个吗?有没有办法让这些黑色边框透明?
编辑
我还应该提到干预是使用 php 的默认 GD 库进行图像处理。
【问题讨论】:
【参考方案1】:能够通过使用干预的canvas() 方法创建单独的图像来解决此问题。然后我在裁剪后的图像上使用trim() 来移除周围的边框,并将该图像插入到新画布图像的中心。有点复杂,而且很慢(服务器上 3-4 秒),但它解决了问题。仍然对更好的解决方案持开放态度(如果有的话)。
public function saveLogo(int $userId, array $params) : bool
try
$org = $this->userService->getUserDefaultOrg($userId);
$newImageName = $org->slug . '-' . uniqid() . '.png';
$cropped = Image::make(getenv('TMP_ORG_LOGOS') . $params['filename'])
->crop(round($params['width']), round($params['height']),
round($params['x']), round($params['y']))
->encode('png', 100)->trim();
$canvas = \Image::canvas(round($params['width']), round($params['height']));
$canvas->insert($cropped, 'center');
$canvas->save(getenv('ORGANIZATION_LOGOS_DIRECTORY') . $newImageName, 100);
$org->logo = $newImageName;
$org->save();
return true;
catch (\Exception $e)
return false;
【讨论】:
【参考方案2】:#Importing modules opencv + numpy
import cv2
import numpy as np
#Reading an image (you can use PNG or JPG)
img = cv2.imread('Robo.jpg')
## 0.5 means 50% of image to be scaling
img = cv2.resize(img,None,fx=0.5,fy=0.5)
# black
img1 = np.zeros((600,600,3))
#Getting the bigger side of the image
s = max(img1.shape[0:2])
#Creating a dark square with NUMPY
f = np.zeros((s,s,3),np.uint8)
#Getting the centering position
ax,ay = (s - img.shape[1])//2,(s - img.shape[0])//2
#Pasting the 'image' in a centering position
f[ay:img.shape[0]+ay,ax:ax+img.shape[1]] = img
#Showing results (just in case)
cv2.imshow("IMG",f)
cv2.imshow("IMG2",img)
#A pause, waiting for any press in keyboard
cv2.waitKey(0)
#Saving the image
# cv2.imwrite("img2square.png",f)
cv2.destroyAllWindows()
【讨论】:
以上是关于干预裁剪后的 png 图像周围的黑色边框的主要内容,如果未能解决你的问题,请参考以下文章