[英]How to convert image into base64 encoding format
我有一個包含從imagecopyresampled
函數返回的圖像的變量,我想將此變量轉換為base64編碼格式以返回到我的JavaScript文件。 錯誤是base64_encode
和exif_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;
?>
這會起作用
$image = 'folder/your_image.png';
$type = pathinfo($image, PATHINFO_EXTENSION);
$imgdata = file_get_contents($image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($imgdata);
用於圖像復制重新采樣
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.