2017-08-03 16 views
2

画像ファイルのサイズが800x600で、この800x600を400x300にリサイズし、両方の画像(800x600と400x300)をデータベースbase64_encode形式で保存します。データベースの最初のイメージ(800x600)に保存できますが、2番目のイメージ(400x300)をbase64_encode形式に変換してデータベースに保存する方法はありますか?私は2つの入力フィールドを使いたくありません。私はそれのために十分な1つの入力フィールドと思います。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); 

答えて

2

あなたは最初のものから新しいイメージを作成するための小さなスクリプトを作成し、それに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 

EDIT 1

それはせずにそれを行うことが可能です第2のイメージのためのディレクトリを使用していますが、それはかなりトリッキーです。

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

私のファイルはbase64_encode形式でデータベースに直接保存されます。私は目的地のフォルダを使いたくない。データベース内の保存先パスの2番目のイメージを使用せずに可能ですか? –

+0

編集が完了しました。可能です。 – Latsuj

+0

ありがとうございます.15kbのように2番目の画像サイズを小さくすることができます。 2番目の画像がサムネイル用に使用されるためです。 –