我正在尝试裁剪图像,使用图像的某些部分,但也允许在其周围添加"额外"空间。但是,当裁剪后的图像在"额外"空间中生成黑色空间时,当我希望它是透明的时。
使用 cropper JavaScript 获取裁剪坐标:https://fengyuanchen.github.io/cropperjs/
然后使用 PHP imagecopyresample
d 将图像裁剪为大小。
的裁剪很好,但是如果我将图像裁剪为大于原始大小,它会在图像周围添加黑色空间,我想将其更改为透明。
研究在裁剪后的图像中搜索黑色像素并将其转换为透明,但是当图像中有黑色时,这个想法就被打破
了 Current php code: (asuming file type is PNG)
//$cropData
//is an array of data passed through from the cropper containing the original width and height, new width and height and the cropping x and y coordinates.
//passed in image to be cropped
$current_image = "/folder/example.jpg";
//image file location of cropped image
$image_name = "/folder/cropped_example.jpg";
//create blank image of desired crop size
$width = $cropData["width"];
$height = $cropData["height"];
$background = imagecreatetruecolor($width, $height);
//crop coordinates
$crop_x = $cropData["x"];
$crop_y = $cropData["y"];
//create resouce image of current image to be cropped
$image = imagecreatefrompng($current_image);
//crop image
imagecopyresampled($background, $image, 0, 0, $crop_x, $crop_y, $width, $height, $width, $height)){
imagepng($background, $image_name);
//File Uploaded... return to page
- 首先,您需要通过将
true
传递给imagesavealpha
来启用 alpha 通道 - 下一步是通过将
false
传递给imagealphablending
来禁用 alpha 混合 否则,alpha 通道将用于重新计算颜色,其值将丢失。 - 将传递 127 作为 alpha 值的透明颜色分配给
imagecolorallocatealpha
- 用这种颜色填充源图像的背景(例如调用
imagefilledrectangle
( - 将源宽度和高度参数传递给
imagecopyresampled
时,不要超过图像的实际大小,否则越界区域将被视为不透明黑色。
例:
$background = imagecreatetruecolor($width, $height);
//crop coordinates
$crop_x = 10;
$crop_y = 10;
imagesavealpha($background, true); // alpha chanel will be preserved
imagealphablending($background, false); // disable blending operations
$transparent_color = imagecolorallocatealpha($background, 0, 0, 0, 127); // allocate transparent
imagefilledrectangle($background, 0, 0, $width, $height, $transparent_color); // fill background
//create resouce image of current image to be cropped
$image = imagecreatefrompng($current_image);
// Limit source sizes;
$minw = min($width, imagesx($image));
$minh = min($height, imagesy($image));
//crop image
imagecopyresampled($background, $image, 0, 0, $crop_x, $crop_y, $minw, $minh, $minw, $minh);
imagepng($background, $image_name);
// done!