我正在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库进行图像处理。
答案 0 :(得分:0)
能够通过使用干预的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;
}
}
答案 1 :(得分:0)
#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()