サーバ側で何かしらの処理を実行し、その結果に基づいてクライアント側に画像を返したい場合、Codeigniterに用意されている出力クラスを使うと便利です。
※画像以外にも任意のファイル形式を返す場合に有効です
imgタグのsrc属性に直接URLを指定したり、JavaScriptのImageクラスを動的に生成したりするときに使用することで、画像を簡単に表示することができます。
画像のURLのみを返すような処理であれば、画像そのものを返してしまった方が実装コストが低くて済むと思います。
コントローラーのサンプル
※画像($file_path)は適当に用意してパスを合わせてください。
Image_responder.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image_responder extends CI_Controller {
public function get_image()
{
$file_path = '/work/sample.png';
$this->output
->set_content_type('jpeg')
->set_output(file_get_contents($file_path));
}
}
HTMLのサンプル
※URLの部分は環境に合わせてください
TEST.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Codeigniter Test</title>
<style>
#request {
display: block;
padding: 10px;
margin: auto;
margin-top: 10px;
}
#results {
display: flex;
justify-content: center;
background-color: rgba(0,0,0,.5);
margin-top: 10px;
min-height: 64px;
}
#results > img {
width: 64px;
box-sizing: border-box;
padding: 5px;
}
</style>
<script type="text/javascript">
function getImage() {
const img = new Image();
img.onload = function (e) {
document.getElementById('results').appendChild(img);
};
img.src = 'http://xxxxx.yyyy.zzz/index.php/Image_responder/get_image';
}
</script>
</head>
<body>
<input type="button" value="request" id="request" onclick="getImage();">
<div id="results"></div>
</body>
</html>
```
### 実行結果イメージ

