我正在尝试使用图像的某些部分来裁剪图像,但还希望在图像周围添加“额外”空间。但是,当裁剪后的图像在“多余”空间中产生黑色空间时,我希望它是透明的。
使用裁剪器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
答案 0 :(得分:0)
true
传递到imagesavealpha
来启用Alpha通道false
传递到imagealphablending
来禁用alphablending,否则alpha通道将用于重新计算颜色,并且其值将丢失。imagecolorallocatealpha
分配将127作为alpha值传递的透明颜色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!