Php 从base64_encode调整图像大小

Php 从base64_encode调整图像大小,php,image,base64,encode,image-resizing,Php,Image,Base64,Encode,Image Resizing,我的图像文件大小为800x600,我想将此800x600调整为400x300,然后以数据库base64_编码格式保存这两个图像(800x600和400x300)。我可以将第一个图像(800x600)保存在数据库中,但如何将第二个图像(400x300)转换为base64_编码格式并保存在数据库中?我不想使用两个输入字段。我认为一个输入字段就足够了 $image = ($_FILES["my_image"]["name"]); $theme_image = (

我的图像文件大小为800x600,我想将此800x600调整为400x300,然后以数据库base64_编码格式保存这两个图像(800x600和400x300)。我可以将第一个图像(800x600)保存在数据库中,但如何将第二个图像(400x300)转换为base64_编码格式并保存在数据库中?我不想使用两个输入字段。我认为一个输入字段就足够了

$image              = ($_FILES["my_image"]["name"]);
$theme_image        = ($_FILES["my_image"]["tmp_name"]);
$bin_string         = file_get_contents("$theme_image"); 
$theme_image_enc    = base64_encode($bin_string); 

您必须制作一个小脚本,从第一个图像创建新图像,并对其进行base64_编码

$WIDTH                  = 400; // The size of your new image
$HEIGHT                 = 300;  // The size of your new image
$QUALITY                = 100; //The quality of your new image
$DESTINATION_FOLDER = DependOfYourRepository; // The folder of your new image

// The directory where is your image
$filePath = DependOfYourRepository; 

// This little part under depend if you wanna keep the ratio of the image or not
list($width_orig, $height_orig) = getimagesize($filePath);
$ratio_orig = $width_orig/$height_orig;
if ($WIDTH/$HEIGHT > $ratio_orig) {
    $WIDTH = $HEIGHT*$ratio_orig;
} else {
    $HEIGHT = $WIDTH/$ratio_orig;
}

// The function using are different for png, so it's better to check
if ($file_ext == "png") {
    $image = imagecreatefrompng($filePath);
} else {
    $image = imagecreatefromjpeg($filePath);
}

// I create the new image with the new dimension and maybe the new quality
$bg = imagecreatetruecolor($WIDTH, $HEIGHT);
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopyresampled($bg, $image, 0, 0, 0, 0, $WIDTH, $HEIGHT, $width_orig, $height_orig);
imagedestroy($image);
imagejpeg($bg, $DESTINATION_FOLDER.$filename, $QUALITY);
$bin_string_little = file_get_contents($DESTINATION_FOLDER.$filename); 
// I remove the image created because you just wanna save the base64 version
unlike($DESTINATION_FOLDER.$filename);
imagedestroy($bg);
$theme_image_enc_little =  base64_encode($bin_string_little); 
// And now do what you want with the result 
编辑1

不使用第二个映像的目录也可以这样做,但这相当棘手

$theme_image_little = imagecreatefromstring(base64_decode($theme_image_enc));
$image_little = imagecreatetruecolor($WIDTH, $HEIGHT);
// $org_w and org_h depends of your image, in your case, i guess 800 and 600
imagecopyresampled($image_little, $theme_image_little, 0, 0, 0, 0, $WIDTH, $HEIGHT, $org_w, $org_h);

// Thanks to Michael Robinson
// start buffering
ob_start();
imagepng($image_little);
$contents =  ob_get_contents();
ob_end_clean();

$theme_image_enc_little = base64_encode($contents):

我的文件以base64_编码格式直接保存在数据库中。我不想使用目标文件夹。在不使用目标路径的情况下,是否可以将第二个图像保存在数据库中?谢谢,可以使第二个图像的大小更小,如15kb。因为第二个图像将用于缩略图。