从base64编码调整图像大小

3
我的图像文件大小为800x600,我想将这个800x600的图像大小调整为400x300,然后将这两个图像(800x600和400x300)以base64_encode格式保存在数据库中。我可以先保存第一个图像(800x600)到数据库中,但是如何将第二个图像(400x300)转换为base64_encode格式并保存到数据库中呢?我不想使用两个输入字段,我认为一个输入字段就足够了。
$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); 
1个回答

3

您需要编写一个小脚本,从第一张图片创建新图像并对其进行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_encode格式直接保存在数据库中,我不想使用目标文件夹。不使用目标路径,是否可以将第二张图片保存在数据库中? - user7984120
谢谢,能否将第二张图片的大小缩小到15kb左右。因为第二张图片将用作缩略图。 - user7984120

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接