// 创建源图像对象$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
);
?>