如何将图像转换为base64编码格式

时间:2017-07-01 10:09:03

标签: javascript php encoding

我有一个包含从imagecopyresampled函数返回的图像的变量,我想将此变量转换为base64编码格式以返回到我的JavaScript文件。 错误是base64_encodeexif_imagetype功能不将图像作为输入。 这是我的代码:

<?php

$img_name     = $_POST['name'];
$data         = file_get_contents($img_name);
$crop_start_x = $_POST['crop_start_x'];
$crop_start_y = $_POST['crop_start_y'];
$crop_width   = $_POST['crop_width'];
$crop_height  = $_POST['crop_height'];

$dst_x = 0;
$dst_y = 0;
$src_x = $crop_start_x;
$src_y = $crop_start_y;
$dst_w = $crop_width;
$dst_h = $crop_height;
$src_w = $src_x + $dst_w;
$src_h = $src_y + $dst_h;

$dst_image = imagecreatetruecolor($dst_w, $dst_h);
$src_image = imagecreatefromstring($data);

imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

$type         = exif_imagetype($dst_image);
$base64_image = 'data:image/' . $type . ';base64,' . base64_encode($dst_image);

echo $base64_image;

?>

1 个答案:

答案 0 :(得分:0)

这将有效

$image = 'folder/your_image.png';
$type = pathinfo($image, PATHINFO_EXTENSION);
$imgdata = file_get_contents($image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($imgdata);

for imagecopyresampled

imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
ob_start();
imagejpeg($dst_image, null);
$img = ob_get_clean();
$base64 = base64_encode($img)