首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将图像裁剪到大于原始大小

将图像裁剪到大于原始大小
EN

Stack Overflow用户
提问于 2019-07-23 19:33:01
回答 1查看 421关注 0票数 1

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

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

然后使用PHP imagecopyresampled将图像裁剪成合适的大小。

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

查看了在裁剪后的图像中搜索黑色像素并将其转换为透明像素,但是当图像中有黑色像素时,这种想法就会中断

代码语言:javascript
复制
 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
EN

回答 1

Stack Overflow用户

发布于 2019-07-23 20:42:48

alpha通道首先您需要通过将true传递给imagesavealpha

  • 来启用alpha通道。下一步是通过将false传递给imagealphablending来禁用字母混合,否则alpha通道将被用来重新计算颜色并且它的值将丢失。

  • 分配一个传递127作为Alpha值的透明色,以便通过该颜色来传递源图片的背景(例如,调用imagefilledrectangle)

  • When将源的宽度和高度参数传递给<

>D16不要超过图片的实际大小,否则,越界区域将被假定为不透明黑色。

示例:

代码语言:javascript
复制
 $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!
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57163266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档