2017-07-01 65 views
0

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

<?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; 

?> 

回答

0

这将工作

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

为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) 
+0

看到这个代码需要$图像的路径上这就是为什么PATHINFO和BASE64_ENCODE的作品,但在我case我有dst_image作为从imagecopyresampled函数返回,有类型差异。 – user3661745

+0

编辑了上面的代码,现在你可以试试这个@ user3661745 – Prags

+0

Ok Thankyou这个工作。我想把这个字符串返回到JavaScript并解码它显示。你能帮我解决这个问题吗? – user3661745