php转webp

乒乓球| 阅读:581 发表时间:2024-01-02 15:49:15 科技智能

// 创建源图像对象$source

=

imagecreatefromjpeg

(

'input_image.jpg'

);

// 根据输入图像类型选择相应函数

// 设置目标图像属性$width

=

imagesx

(

$source

);

$height

=

imagesy

(

$source

);

$target

=

imagecreatetruecolor

(

$width

,

$height

);

imagesavealpha

(

$target

,

true

);

$transparentColor

=

imagecolorallocatealpha

(

$target

,

0

,

0

,

0

,

127

);

imagefill

(

$target

,

0

,

0

,

$transparentColor

);

// 复制并调整透明度for

(

$i

=

0

;

$i

<

$width

; ++

$i

) {

for

(

$j

=

0

;

$j

<

$height

; ++

$j

) {

$rgba

=

imagecolorsforindex

(

$source

,

imagecolorat

(

$source

,

$i

,

$j

));

if

(

isset

(

$rgba

[

'alpha'

]) &&

$rgba

[

'alpha'

] !==

0

) {

$newAlpha

=

round

((

$rgba

[

'alpha'

] /

127

) *

128

);

$newRgba

= [

'red'

=>

$rgba

[

'red'

],

'green'

=>

$rgba

[

'green'

],

'blue'

=>

$rgba

[

'blue'

],

'alpha'

=>

$newAlpha

];

$targetPixel

=

imagecolorclosestalpha

(

$target

, ...

array_values

(

$newRgba

));

imagesetpixel

(

$target

,

$i

,

$j

,

$targetPixel

);

}

elseif

(!

empty

(

$rgba

)) {

$targetPixel

=

imagecolorclosestalpha

(

$target

, ...

array_values

(

$rgba

));

imagesetpixel

(

$target

,

$i

,

$j

,

$targetPixel

);

}

}

}

// 保存为WebP格式imagewebp

(

$target

,

'output_image.webp'

,

95

);

// 第三个参数表示质量,取值范围从0到100imagedestroy

(

$source

);

imagedestroy

(

$target

);

?>


*文章为投稿者独立观点,不代表本站站长的立场
本文由相遇青春-Yn发表并编辑,转载此文章须经作者同意,并请附上出处及本页链接。如有侵权,请联系本站删除。

热门推荐