0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Codeigniterを使ってレスポンスで画像を返す

Posted at

サーバ側で何かしらの処理を実行し、その結果に基づいてクライアント側に画像を返したい場合、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>
```

### 実行結果イメージ
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/613298/4f8bfb10-edf5-dff0-2d35-0f7a85f86cb0.png)


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/613298/7fd38977-d6d2-18ae-0f79-b9dc45b638f1.png)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?