Programing

PHP에서 이미지 출력

crosscheck 2020. 11. 13. 07:49
반응형

PHP에서 이미지 출력


나는 이미지가 $file(예를 들어 ../image.jpg)

마임 유형이있는 $type

어떻게 브라우저에 출력 할 수 있습니까?


$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);

웹 서버를 직접 구성 할 수있는 자유가 있다면 mod_xsendfile (Apache 용) 과 같은 도구 가 PHP에서 파일을 읽고 인쇄하는 것보다 훨씬 낫습니다. PHP 코드는 다음과 같습니다.

header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();

mod_xsendfile은 X-Sendfile 헤더를 선택하고 파일을 브라우저 자체로 보냅니다. 이것은 특히 큰 파일의 경우 성능에 실질적인 차이를 만들 수 있습니다. 대부분의 제안 된 솔루션은 전체 파일을 메모리로 읽어 들인 다음 인쇄합니다. 20kbyte 이미지 파일의 경우 괜찮지 만 200MB TIFF 파일이 있으면 문제가 발생할 수 있습니다.


$file = '../image.jpg';

if (file_exists($file))
{
    $size = getimagesize($file);

    $fp = fopen($file, 'rb');

    if ($size and $fp)
    {
        // Optional never cache
    //  header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
    //  header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    //  header('Pragma: no-cache');

        // Optional cache if not changed
    //  header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');

        // Optional send not modified
    //  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and 
    //      filemtime($file) == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
    //  {
    //      header('HTTP/1.1 304 Not Modified');
    //  }

        header('Content-Type: '.$size['mime']);
        header('Content-Length: '.filesize($file));

        fpassthru($fp);

        exit;
    }
}

http://php.net/manual/en/function.fpassthru.php


header('Content-type: image/jpeg');
readfile($image);

이 시도:

<?php
  header("Content-type: image/jpeg");
  readfile("/path/to/image.jpg");
  exit(0);
?>

이 문제를 겪는 다음 남자 또는 여자를 위해 다음은 나를 위해 일한 것입니다.

ob_start();
header('Content-Type: '.$mimetype);
ob_end_clean();
$fp = fopen($fullyQualifiedFilepath, 'rb');
fpassthru($fp);
exit;

당신은 그 모든 것이 필요합니다. MIME 유형이 다른 경우 PHP의 mime_content_type ($ filepath)을 살펴보십시오.


<?php

header("Content-Type: $type");
readfile($file);

그것이 짧은 버전입니다. 일을 더 멋지게 만들기 위해 할 수있는 몇 가지 추가 작업이 있지만 그게 효과가있을 것입니다.


헤더사용 하여 올바른 Content-type을 보낼 수 있습니다 .

header('Content-Type: ' . $type);

그리고 readfile이미지의 내용을 출력하려면 :

readfile($file);


그리고 아마도 (아마도 필요하지는 않지만 경우에 따라) Content-Length 헤더도 보내야 할 것입니다.

header('Content-Length: ' . filesize($file));


참고 : 이미지 데이터 (예 : 공백 없음) 외에는 출력하지 마십시오. 그렇지 않으면 더 이상 유효한 이미지가 아닙니다.


You can use finfo (PHP 5.3+) to get the right MIME type.

$filePath = 'YOUR_FILE.XYZ';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($finfo, $filePath);
finfo_close($finfo);

header('Content-Type: ' . $contentType);
readfile($filePath);

PS: You don't have to specify Content-Length, Apache will do it for you.


    $file = '../image.jpg';
    $type = 'image/jpeg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    $img = file_get_contents($file);
    echo $img;

This is works for me! I have test it on code igniter. if i use readfile, the image won't display. Sometimes only display jpg, sometimes only big file. But after i changed it to "file_get_contents" , I get the flavour, and works!! this is the screenshoot: Screenshot of "secure image" from database


(Expanding on the accepted answer...)

I needed to:

  1. log views of a jpg image and an animated gif, and,
  2. ensure that the images are never cached (so every view is logged), and,
  3. also retain the original file extensions.

I accomplished this by creating a "secondary" .htaccess file in the sub-folder where the images are located.
The file contains only one line:

AddHandler application/x-httpd-lsphp .jpg .jpeg .gif

In the same folder, I placed the two 'original' image files (we'll call them orig.jpg and orig.gif), as well as two variations of the [simplified] script below (saved as myimage.jpg and myimage.gif)...

<?php 
  error_reporting(0); //hide errors (displaying one would break the image)

  //get user IP and the pseudo-image's URL
  if(isset($_SERVER['REMOTE_ADDR'])) {$ip =$_SERVER['REMOTE_ADDR'];}else{$ip= '(unknown)';}
  if(isset($_SERVER['REQUEST_URI'])) {$url=$_SERVER['REQUEST_URI'];}else{$url='(unknown)';}

  //log the visit
  require_once('connect.php');            //file with db connection info
  $conn = new mysqli($servername, $username, $password, $dbname);
  if (!$conn->connect_error) {         //if connected then save mySQL record
   $conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
     $conn->close();  //(datetime is auto-added to table with default of 'now')
  } 

  //display the image
  $imgfile='orig.jpg';                             // or 'orig.gif'
  header('Content-Type: image/jpeg');              // or 'image/gif'
  header('Content-Length: '.filesize($imgfile));
  header('Cache-Control: no-cache');
  readfile($imgfile);
?>

The images render (or animate) normally and can be called in any of the normal ways for images (like an <img> tag), and will save a record of the visiting IP, while invisible to the user.


<?php $data=file_get_contents(".../image.jpg" );header("Content-type: image/png"); echo $data; ?>

The first step is retrieve the image from a particular location and then store it on to a variable for that purpose we use the functio file_get_contents() with the destination as the parameter. Next we set the content type of the output page as image type using the header file. Finally we print the retrieved file using echo.

참고URL : https://stackoverflow.com/questions/1851849/output-an-image-in-php

반응형

'Programing' 카테고리의 다른 글

WebP 지원 감지  (0) 2020.11.13
mongodb에 json 파일 삽입  (0) 2020.11.13
Redis 세트 대 해시  (0) 2020.11.12
IEnumerable은 왜  (0) 2020.11.12
과학 데이터 저장에 대한 NetCDF 대 HDF5에 대한 의견?  (0) 2020.11.12