使用PHP将base64 JPEG转换为透明PNG

时间:2020-06-30 16:51:35

标签: php base64 image-manipulation

我想用我自己的代码将base64 jpeg或jpg(白色背景)转换为透明png:

$img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type); 
$success = file_put_contents($file, $data); //when its done it saves the image data

我正在关注此post,但是图像无法保存到已修改的目录dir中:

    $img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type); 
$success = file_put_contents($file, $data); //when its done it saves the image data

imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $color);
imagepng($img, 'test.png');

此外,在post之后,但打开修改后的图像显示错误:

    $img = str_replace(array('data:image/jpeg;base64', 'data:image/jpg;base64', 'data:image/bmp;base64', 'data:image/png;base64'), '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . $fn . str_replace('image/', '.', $type); 
$success = file_put_contents($file, $data); //when its done it saves the image data

$image = imagealphablending($file, true);
$transparentcolour = imagecolorallocate($image, 255,255,255);
imagecolortransparent($image, $transparentcolour)

0 个答案:

没有答案