gpt4 book ai didi

php - 从 base64_encode 调整图像大小

转载 作者:行者123 更新时间:2023-12-05 04:09:41 25 4
gpt4 key购买 nike

我的图像文件大小是 800x600,我想将这个 800x600 的大小调整为 400x300,然后以数据库 base64_encode 格式保存两个图像(800x600 和 400x300)。我可以将第一张图像 (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);

最佳答案

你必须编写一个小脚本来从第一个图像创建新图像并在其上进行 base64_encode

$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):

关于php - 从 base64_encode 调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45478827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com