php - 将图像裁剪为大于原始尺寸
问题描述
我正在尝试裁剪图像,使用图像的某些部分,但也允许在其周围添加“额外”空间。但是,当裁剪的图像在“额外”空间中生成黑色空间时,我希望它是透明的。
使用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
来启用 Alpha 通道imagesavealpha
- 下一步是通过传递来禁用 alphablending
false
否则imagealphablending
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!
推荐阅读
- c# - ASP.NET Core Json 对象的格式很奇怪,使用 \u0022
- json - 使用 SwiftyJSON 解析 JSON 响应
- reactjs - 如何使用 React Link 和 Routes 修复此错误
- javascript - React:如何在没有 PUBLIC_URL 出现在路由中的情况下提供资产?
- c# - 根据类的当前实现,通过直接枚举将 ConcurrentDictionary 复制到普通字典是否安全?
- java - java.lang.IllegalArgumentException:在方法名称中发现无效字符。HTTP 方法名称必须是 Spring 和 Android 中的标记
- textx - 父级中的引用属性
- adsense - 在 AdSense 广告上获得无效点击 - 以前从未见过
- netlify - 从 netlify 函数运行动物群 FQL 查询时出错
- javascript - Javascript querySelector 给出 null