【问题标题】:Cropping an image into Hexagon shape in a web page在网页中将图像裁剪为六边形
【发布时间】:2012-02-05 10:10:14
【问题描述】:

我在网页中有一张图片。我想将四面图像转换为六面图像。即裁剪边缘并将图像转换为六边形。

如何在我的服务器端使用 PHP ImageMagick/GD。我正在使用 XAMPP 服务器构建示例网页。或者有没有更好的方法通过使用 img 样式属性来使用 Javascript/CSS。

【问题讨论】:

  • 你可以在服务器端使用什么,ImageMagick? GD?
  • 您大概知道您不能拥有实际上六面的图像?除非它是矢量图形,否则浏览器需要插件才能显示,而 PHP 不会 成为创建语言...

标签: php css image


【解决方案1】:

在 CSS 中会更痛苦(你甚至不需要 JS)。

看到这个小提琴http://jsfiddle.net/kizu/bhGn4/

【讨论】:

  • 现在这是一些值得big +1 的简洁CSS。我想你把那个藏在什么地方了?如果你写得这么快,我非常印象深刻......
  • 是的,我从未说过这是我的。自去年 9 月以来,我已将其添加为书签;)
【解决方案2】:

因为我需要使用多种尺寸和缓存,所以我需要在 php 中使用它(好吧,服务器端:)):

// doge.jpg is a squared pic
$raw = imagecreatefromjpeg('doge.jpg'); 

/* Simple math here

  A_____F
  /     \
B/       \E
 \       /
 C\_____/D

*/
$w = imagesx($raw); 
$points = array(
    .25 * $w, .067  * $w, // A 
    0, .5   * $w, // B
    .25 * $w, .933  * $w, // C
    .75 * $w, .933  * $w, // D
    $w, .5  * $w, // E
    .75 * $w, .067  * $w  // F
);

// Create the mask
$mask = imagecreatetruecolor($w, $w);
imagefilledpolygon($mask, $points, 6, imagecolorallocate($mask, 255, 0, 0));

// Create the new image with a transparent bg
$image = imagecreatetruecolor($w, $w);
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagealphablending($image, false);
imagesavealpha($image, true);
imagefill($image, 0, 0, $transparent);

// Iterate over the mask's pixels, only copy them when its red.
// Note that you could have semi-transparent colors by simply using the mask's 
// red channel as the original color's alpha.
for($x = 0; $x < $w; $x++) {
    for ($y=0; $y < $w; $y++) { 
        $m = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));
        if($m['red']) {
            $color = imagecolorsforindex($raw, imagecolorat($raw, $x, $y));
            imagesetpixel($image, $x, $y, imagecolorallocatealpha($image,
                              $color['red'], $color['green'], 
                              $color['blue'], $color['alpha']));
        }
    }
}

// Display the result
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

你应该得到类似这样的东西:

【讨论】:

  • 你知道如何在 laravel 中做到这一点吗?我们也可以将六边形旋转 90 度吗?
【解决方案3】:

您可以使用 HTML5 画布遮盖边缘,然后使用数据 URI 读出图像。

另外请注意,要使这项技术发挥作用,您必须将图像代理到您的域,因为如果从外部域加载图像,Canvas 会将其内容标记为脏。

更新:我添加了一个 jsfiddle 来演示这种技术。

【讨论】:

  • @Krof Drakula:我在 jsfiddle 中找不到任何东西。我错过了什么吗?
  • 忘记点击“更新”,现已修复。
猜你喜欢
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2012-10-08
  • 2013-07-12
  • 2016-05-01
相关资源
最近更新 更多