2010-12-03 4 views

답변

23

데이터 URL을 만드시겠습니까? MIME-Type과 기타 몇 가지 추가 정보가 필요합니다 (Wikipedia 참조).

$b64image = base64_encode(file_get_contents('path/to/image.png')); 

관련 문서 : base64_encode()-function, file_get_contents()-function이 경우가 아니라면,이 이미지의 단순한 base64로 표현 될 것이다.

8

이 시도 : -

예제 1 : -

<?php 
function base64_encode_image ($filename=string,$filetype=string) { 
    if ($filename) { 
     $imgbinary = fread(fopen($filename, "r"), filesize($filename)); 
     return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary); 
    } 
} 
?> 

used as so 

<style type="text/css"> 
.logo { 
    background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px; 
} 
</style> 

or 

<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/> 

예제 2를 -

$path= 'myfolder/myimage.png'; 
$type = pathinfo($path, PATHINFO_EXTENSION); 
$data = file_get_contents($path); 
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); 
+0

예 2는 내가 찾고있는 것입니다. +1. –

4

내가 비슷한 솔루션을 찾고이 질문에 도착, 실제로, 나는 이것이 원래의 질문이라는 것을 이해했습니다.

나는 같은 일을하고 싶어하지만, 파일이 원격 서버에, 그래서 이것은 내가 무슨 짓을 :

$url = 'http://yoursite.com/image.jpg'; 
$image = file_get_contents($url); 
if ($image !== false){ 
    return 'data:image/jpg;base64,'.base64_encode($image); 

} 

그래서,이 코드는 문자열을 반환하는 함수에서, 당신은 할 수 html의 img 태그의 src 매개 변수 안에 반환 값을 출력합니다. 내 templating 라이브러리로 smarty를 사용하고 있습니다. 그것은 다음과 같이 갈 수 :

<img src="<string_returned_by_function>"> 

주에게로 명시 적으로 호출 :

if ($image !== false) 

file_get_contents 파일 가져 오기가 성공적 경우에도 0을 반환 할 수 있습니다 어떤 경우에는 false로 주조 할 수 있기 때문이 필요 . 실제로이 경우에는 발생하지 않아야하지만 파일 내용을 가져올 때 좋은 방법입니다.

관련 문제