web-dev-qa-db-ja.com

file_get_contentsを使用して画像を表示

phpでfile_get_contentsを使用して取得した画像を表示するにはどうすればよいですか?

ヘッダーを変更して、それをエコーするだけか何かが必要ですか?

ありがとう!

40
Belgin Fish

ヘッダーを変更して、それをエコーするだけか何かが必要ですか?

正確に。

header("content-type: image/your_image_type");とデータを後で送信します。

30
Pekka 웃

readfile を使用して、次のように getimagesize から取得できる画像ヘッダーを出力できます。

$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);

ここでreadfileを使用する必要があるのは、 file_get_contents がファイルをメモリに読み込む出力バッファにファイルを直接出力するためです。

66
robjmills
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="' . $src . '">';
47
Yaşar Xavan

それを行うこともできますし、readfile関数を使用して出力することもできます:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

編集:Derp、明白なギラギラしたタイプミスを修正。

9
Mike Caron

あなたはこのようにすることができます:

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>
8

@seengee回答の小さな編集:動作させるには、変数を中括弧で囲む必要があります。そうしないと、エラーが発生します。

header("Content-type: {$imginfo['mime']}");

0
darighteous1