にっきダイアリー

はてなダイアリーからはてなblogに移動してみました。

データスキームを使って画像ファイルを埋め込んだimgタグを作成する

(20110808追記:も少しまともに作り直してみた。)
せっかく途中まで作ったけど、今回は使わなさそうなのでいつか使う時のためにメモとして残しておく。
再利用の際は、キャッシュと元ファイルの日付調べてキャッシュが古かったら再生成するっての付け加えるのと、imgタグのaltとサイズちゃんと反映するようにするのと、せっかく投げてる例外をきちんと処理するのと忘れないよう>未来の自分。

<?php 
// 例外を使う
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

if(!defined('THUMB_CACHE_EXT')) define('THUMB_CACHE_EXT','.b64'); // キャッシュにくっつける拡張子
if(!defined('THUMB_DIR')) define('THUMB_DIR',''); // サムネールがあるディレクトリ
if(!defined('THUMB_CACHE_DIR')) define('THUMB_CACHE_DIR',''); // キャッシュを保存するディレクトリ

// base64でエンコードした画像データをIMGタグの中に埋め込んで返す
// 参考 : http://en.wikipedia.org/wiki/Data_URI_scheme
function get_thumb_itag($tfile,$alt='',$x=0,$y=0,$odir='',$cdir=''){
	if(!$odir) $odir = THUMB_DIR;
	if(!$cdir) $cdir = THUMB_CACHE_DIR;
	$ofile = $odir.$tfile;
	$cfile = $cdir.$tfile.THUMB_CACHE_EXT;
	try{
		if(file_exists($cfile)){
			$txt = file_get_contents($cfile);
		}
		else{
			$bin = file_get_contents($ofile);
			$txt = base64_encode($bin);
			fwrite(fopen($cfile, "w"), $txt, strlen($txt)); // cache保存
		}
	}
	catch (Exception $e) {
		var_dump($e->getMessage());
	}
	if($txt){
		$itag = '<img src="data:image/jpeg;base64,'.$txt.'" alt="sample"/>';
	}
	else{
		$itag = 'えらーだって';
	}
	return $itag;
}

// 指定のキャッシュ削除
function delete_thumb_cache($tfile,$cdir=''){
	if(!$cdir) $cdir = THUMB_CACHE_DIR;
	$cfile = $cdir.$tfile.THUMB_CACHE_EXT;
	try{
		unlink($cfile);
	}
	catch (Exception $e) {
		var_dump($e->getMessage());
	}
	return 1;
}

?>
<?php echo get_thumb_itag('sample.jpg');?>