1

我正在尝试裁剪图像,使用图像的某些部分,但也允许在其周围添加“额外”空间。但是,当裁剪的图像在“额外”空间中生成黑色空间时,我希望它是透明的。

使用cropper JavaScript 获取裁剪坐标:https ://fengyuanchen.github.io/cropperjs/

然后使用 PHP imagecopyresampled 将图像裁剪为大小。

图像的裁剪很好,但是如果我将图像裁剪为大于原始尺寸,它会在图像周围添加黑色空间,我想将其更改为透明。

研究了在裁剪后的图像中搜索黑色像素并将它们转换为透明的,但是当图像中有黑色时,这个想法就会中断

 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
4

1 回答 1

0
  1. 首先,您需要通过传递true来启用 Alpha 通道imagesavealpha
  2. 下一步是通过传递来禁用 alphablendingfalse否则imagealphablendingalpha 通道将用于重新计算颜色并且其值将丢失。
  3. 分配一个透明颜色,将 127 作为 alpha 值传递给imagecolorallocatealpha
  4. 用这种颜色填充源图像的背景(例如调用imagefilledrectangle
  5. 在传递源宽度和高度参数时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!
于 2019-07-23T12:42:47.960 回答