BASE64 로 인코딩 한 이미지 data를 직접 HTML 문서에 추가하는 방법 외

 
 

참고 : FireFox에서는 지원되나 현재의 IE6,7에서는 지원안되는 현상 .. - 다른방법 모색중 ㅜ.ㅜ;

 

출처 : http://www.linuxchannel.net/docs/img-src-base64.txt

[제목] 한번의 커넥션으로 이미지 모두 전송하는 방법

(BASE64로 인코딩한 이미지 data를 직접 HTML 문서에 추가하는 방법)

- 작성자 : san2(at)linuxchannel.net
- 작성일 : 2002.05.07
- 수  준 : 초중급
- 내  용 : HTML/PHP

http://www.linuxchannel.net/docs/img-src-base64.txt

이 문서는 이미지를 전송하는 과정에서 여러번의 커넥션
없이 한번으로 모두 전송하는 방법을 소개합니다.

*주의)
서로의 장단점을 정확히 습득함을 요합니다.

reference : http://www.faqs.org/rfcs/rfc2397.html

1. 배경 및 개요
2. "data" URL scheme
3. IMG 태그 형태
4. 이미지 파일을 모두 BASE64로 인코딩 하기
  4-1. 커맨드라인에서 작업하기(파이썬 base64.py)
  4-2. PHP로 인코딩해 보기
5. 인코딩된 data를 HTML에 추가하기
  5-1. 단순 HTML만을 사용할 경우
  5-2. PHP를 사용할 경우
6. 벤치마크(속도대결)
7. 결론
8. 후기

---------------------------------------------------

*문맥상 간혹 경어를 생략했습니다. 양해해 주시길 바랍니다.


1. 배경 및 개요

클라이언트(이하 '웹브라우저')가 특정 HTML문서(new document)를
요청시 맨처음 한번의 커넥션이 이루어지고, 그 다음 HTML문서안에
<IMG> 태그가 만약 10개 있다면, 이는 추가적으로 10번의
재커넥션이 이루어질 수 있다는 점에서 초점을 맞추어 봅니다.

일반적으로 속도를 높이기 위해서 서버에서는 KeepAlive 기능을
사용하지만 상당히 바쁜 서버일 경우는 keepAlive를 off 하는것이
더 효과적입니다(리소스 문제).

이와같이 이미지를 모두 전송받기 위해서 웹브라우저는 추가적인
커넥션을 시도하는데, HTTP 상태코드가 302일 경우는 웹브라우저는
서버에서 이미지를 전송받지 않고 디스크 캐쉬나 메모리캐쉬에서
이미지를 가져와 출력합니다. 반면 302 코드가 아닐 경우는 직접
서버에서 이미지를 전송받습니다.

문제는 후자와 같이 직접 이미지를 전송받는 과정에서 여러번의
커넥션이 이루어지는데, 서버의 부하나 네트워크 장애 등등의
원인으로 상당히 지연되는 경우를 경험했을 겁니다.

이 문서는 이와 같이 이미지를 전송하는 과정에서 여러번의 커넥션
없이 한번으로 모두 전송하는 방법을 소개합니다.

  <IMG ... SRC='data:image/gif;base64,R0lGODdhMQAiAPcA.....'>

HTTP 상태코드 302가 많은 경우는 오히려 역효과적임을 주의하시길
바랍니다.


2. data" URL scheme

RFC 2397에 의하면,

  data:[<mediatype>][;base64],<data>

'[' 와 ']'으로 감싸인 부분은 옵션입니다.

"data:"
일부 어플리케이션에서는 URLs길이 제한이 있으므로 주의함.
(RFC 1866)

<mediatype>
data의 media type(옵션).
만약 이 옵션이 없다면 기본값으로 text/plain;charset=US-ASCII
을 사용함.

";base64"
BASE64로 인코딩되어 있다는 의미(역시 옵션).
이 옵션이 없다면 ASCII, URL 표준 %xx hex 인코딩으로 대체된다.

예: data:,A%20brief%20note
    <A HREF='data:,A%20brief%20note'>test</A>

<data>
실제로 BASE64로 인코딩된 data가 위치하거나 URL hex 인코딩된 문자열이
들어감.


그 외 참고사항,
  dataurl    := "data:" [ mediatype ] [ ";base64" ] "," data
  mediatype  := [ type "/" subtype ] *( ";" parameter )
  data       := *urlchar
  parameter  := attribute "=" value


3. IMG 태그 형태

  <IMG ... SRC='data:image/gif;base64,R0lGODdhMQAiAPcA.....'>
  또는
  <IMG ... SRC='data:;base64,R0lGODdhMQAiAPcA.....'>
  또는
  <IMG ... SRC='data:base64,R0lGODdhMQAiAPcA.....'>

다음의 태그를 긁어서 출력해 보세요..

<IMG BORDER=1 SRC="data:image/gif;base64,
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
zxIFBAA7">
<BR>

뭐가 나오나요?


4. 이미지 파일을 모두 BASE64로 인코딩 하기

이미지 파일을 BASE64로 인코딩하면 약간 파일이 커짐에
주의하도록 합니다(약 30%이상 커짐).


4-1. 커맨드라인에서 작업하기(파이썬 base64.py)

다른 툴이 있는지 모르겠지만 필자는 커맨드라인에서
다음의 파이썬 스크립트를 이용한다.

/usr/lib/python1.5/base64.py

$ alias base64='/usr/lib/python1.5/base64.py'

BASE64로 인코딩하려면 ?
(옵션이 없거나 -e 옵션 사용)

$ base64 -e foobar.gif > foobar.gif.enc

디코딩하려면?
(-d 옵션 사용)

$ base64 -e foobar.gif.enc > foobar.gif

다음과 같은 간단한 쉘스크립트를 이용해서 파일끝에 .enc를
붙여 인코딩 파일을 생성합니다.

-- img2base64.sh -------------------------------
#!/bin/sh
#
fpath=51598
BASE64='/usr/lib/python1.5/base64.py'
OIFS=$IFS
IFS='
'
[ ! -d "$fpath" ] && exit 0
[ ! -s "$BASE64" ] && exit 0

for f in `find $fpath -type f 2>/dev/null` ; do
  echo $f
  $BASE64 -e $f > $f.enc
done

IFS=$OIFS
exit 0
------------------------------------------------

사용법 :

$ sh img2base64.sh /path/to/images/directory


4-2. PHP로 인코딩해 보기

PHP를 사용할 경우 base64_encode()함수를 사용한다.
예:

------------------------------------------------
<?php
fucntion get_file($file)
{
  if($fp = @fopen($file,r)) {
    $content = fread($fp,filesize($file));
    fclose($fp);
  }
  return $content;
}

$imgfile = get_file('foobar.gif');
$imgfile = base64_encode($imgfile);

echo $imgfile;
echo "\n<BR>\n<IMG SRC='data:base64,$imgfile'>\n";
?>
------------------------------------------------


5. 인코딩된 data를 HTML에 추가하기

각각의 이미지 파일마다 BASE64로 인코딩된 파일을 생성했다는
가정입니다.

5-1. 단순 HTML만을 사용할 경우

앞의 IMG 태그 예제와 같이 직접 BASE64로 인코딩하여 그 data를
IMG 태그안에 손수 집어넣어야 합니다.
(상당한 중노동이 필요할 듯......^.^)


5-2. PHP를 사용할 경우

------------------------------------------------
<?php
function get_file($file)
{
  if($fp = @fopen($file,r)) {
    $content = fread($fp,filesize($file));
    fclose($fp);
  }
  return $content;
}

function img_src($imgfile, $border=0, $argument='')
{
  $base64data = get_file('$imgfile.enc'); // encoded img file
  return "<IMG BORDER=$border $argument SRC='data:base64,$base64data'>";
}

echo img_src('images/foobar.gif');
echo "\n<BR>\n";
echo img_src('images/foobar2.gif',1);
echo "\n<BR>\n";
echo img_src('images/foobar3.gif",0,'WIDTH=200 HEIGHT=1');
echo "\n<BR>\n";
echo img_src('images/foobar4.gif',0,"ALT='foobar4'");
?>
------------------------------------------------

위와 같이 직접 이미지 data를 전송하면 재 커넥션 없이 한번의
커넥션만 이루어집니다.
비교적 파일크기가 작고 여러번의 커넥션이 이루어진 홈페이지라면
상당히 유용할 겁니다.
용량이 큰 파일일 경우는 오히려 역효과가 날 수 있습니다.

참고로,
아파치 로그파일에서 이미지 파일에 접근 기록이 없어야
정상입니다.

다만, 주의할 점은
웹서버나 다른 어플리케이션에서 BODY의 길이를 제한하면
에러를 낼 수 있습니다.
또한 다른 장애(?)도 발생할 수 있습니다.

직접 테스트해 보시고
장점과 단점을 서로 비교해 보세요.


6. 벤치마크(속도대결)

start_time :
(1)클라이언트에서 문서 요청 -->
(2)웹서버 처리 -->
(3)클라이언트에게 전송 -->
(4)웹브라우저에서 문서 출력
end_time :

여기에서는, 실제로 웹브라우저가 출력하는데까지의 시간 측정은
상당히 어려우므로(?) (4)번 과정은 제외하고 (1)-(3)번까지의
과정을 wget 과 time으로 시간을 측정해 봅니다.
(wget 이 가져온 결과를 /dev/null로 보냄)

주의할 점은 일반 HTML 문서에는 실제로 링크된 이미지 모두를
가져오는데 까지 시간을 측정해야 합니다.

- 크고 작은 이미지를 여러개 준비합니다
  준비한 이미지를 모두 BASE64로 인코딩합니다.
  (5개 이상으로 자신의 홈페이지 기준).

- 문서1(tmp.html)
  비교기준이 되는 일반 문서를 작성합니다.
  예: <IMG SRC='images/foobar.gif'> 와 같은 형식

- 문서2(tmp.php)
  PHP를 이용해서 한번의 커넥션이 이루어지도록 작성합니다.
  예: <IMG SRC='data:base64,$base64data'>

- 문서3(tmp.enc.html)
  인코딩된 data를 직접 HTML 문서에 추가합니다.
  예: <IMG SRC='data:base64,R0lGODdhMQAiAPcA...>
  하나하나씩 작성하기 힘드므로 문서2에서의 결과를
  저장합니다.

다음과 같은 쉘스크립트를 작성해서 테스트해 봅니다.
가능한 같은 네트워크의 다른 PC에서 테스트해 보세요.

-------------------------------------------------
#!/bin/sh
file=51598
i=0
time {
  while [ $i -lt 100 ] ; do
    wget -q -r -O /dev/null http://www.yourdomain.com/tmp/$file
    i=$(($i+1))
  done
}
exit 0
-------------------------------------------------
$ sh this_script.sh tmp.html
$ sh this_script.sh tmp.php
$ sh this_script.sh tmp.enc.html

아마 결과는 그리 만족하지 않을 겁니다. T.T


7. 결론

먼저 결론을 내리기 전에 필자는 이 문서를 작성해 놓고 상당히
고민했습니다.
이유는, 테스트에 대한 그 객관성이 상당히 결여되어 있고, 또한
당연한 결과인줄 알면서도 무모하게 도전한(?) 아둔한 생각 때문에
...


굳지 결론을 내리자면,

 1) 일반적인 홈페이지일 경우 이 방법은 필요없습니다.

 2) 다만, 웹서버와 웹브라우저 간의 커넥션이 빈번하게 이루어지고
    비교적 이미지가 자주 바뀌는 경우에 유용.

 3) 커넥션 수를 줄여서 그 효과를 볼 수 있는 경우.

 4) 양자를 혼용했을 경우 그 효과를 볼 수 있는 경우.

 5) 특별하게 따로 이미지 파일을 만들고 싶지 않을 경우(하나의
    문서로 제공할경우).


8. 후기

생략(필자의 습관상 붙이는 단원)

__EOF__

========================================================================

출처 : www.faqs.org/rfcs/rfc2397.html

 

RFC 2397 (RFC2397)

Internet RFC/STD/FYI/BCP Archives

RFC Index | RFC Search | Usenet FAQs | Web FAQs | Documents | Cities ]

Alternate Formats: rfc2397.txt | rfc2397.txt.pdf

Comment on RFC 2397

RFC 2397 - The "data" URL scheme


Network Working Group                                      L. Masinter
Request for Comments: 2397                           Xerox Corporation
Category: Standards Track                                  August 1998

                         The "data" URL scheme

Status of this Memo

   This document specifies an Internet standards track protocol for the
   Internet community, and requests discussion and suggestions for
   improvements.  Please refer to the current edition of the "Internet
   Official Protocol Standards" (STD 1) for the standardization state
   and status of this protocol.  Distribution of this memo is unlimited.

Copyright Notice

   Copyright (C) The Internet Society (1998).  All Rights Reserved.

1. Abstract

   A new URL scheme, "data", is defined. It allows inclusion of small
   data items as "immediate" data, as if it had been included
   externally.

2. Description

   Some applications that use URLs also have a need to embed (small)
   media type data directly inline. This document defines a new URL
   scheme that would work like 'immediate addressing'. The URLs are of
   the form:

                    data:[<mediatype>][;base64],<data>

   The <mediatype> is an Internet media type specification (with
   optional parameters.) The appearance of ";base64" means that the data
   is encoded as base64. Without ";base64", the data (as a sequence of
   octets) is represented using ASCII encoding for octets inside the
   range of safe URL characters and using the standard %xx hex encoding
   of URLs for octets outside that range.  If <mediatype> is omitted, it
   defaults to text/plain;charset=US-ASCII.  As a shorthand,
   "text/plain" can be omitted but the charset parameter supplied.

   The "data:" URL scheme is only useful for short values. Note that
   some applications that use URLs may impose a length limit; for
   example, URLs embedded within <A> anchors in HTML have a length limit
   determined by the SGML declaration for HTML [RFC1866]. The LITLEN
   (1024) limits the number of characters which can appear in a single

   attribute value literal, the ATTSPLEN (2100) limits the sum of all
   lengths of all attribute value specifications which appear in a tag,
   and the TAGLEN (2100) limits the overall length of a tag.

   The "data" URL scheme has no relative URL forms.

3. Syntax

       dataurl    := "data:" [ mediatype ] [ ";base64" ] "," data
       mediatype  := [ type "/" subtype ] *( ";" parameter )
       data       := *urlchar
       parameter  := attribute "=" value

   where "urlchar" is imported from [RFC2396], and "type", "subtype",
   "attribute" and "value" are the corresponding tokens from [RFC2045],
   represented using URL escaped encoding of [RFC2396] as necessary.

   Attribute values in [RFC2045] are allowed to be either represented as
   tokens or as quoted strings. However, within a "data" URL, the
   "quoted-string" representation would be awkward, since the quote mark
   is itself not a valid urlchar. For this reason, parameter values
   should use the URL Escaped encoding instead of quoted string if the
   parameter values contain any "tspecial".

   The ";base64" extension is distinguishable from a content-type
   parameter by the fact that it doesn't have a following "=" sign.

4. Examples

   A data URL might be used for arbitrary types of data. The URL

                          data:,A%20brief%20note

   encodes the text/plain string "A brief note", which might be useful
   in a footnote link.

   The HTML fragment:

   <IMG
   SRC="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw
   AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz
   ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp
   a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl
   ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis
   F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH
   hhx4dbgYKAAA7"
   ALT="Larry">

   could be used for a small inline image in a HTML document.  (The
   embedded image is probably near the limit of utility. For anything
   else larger, data URLs are likely to be inappropriate.)

   A data URL scheme's media type specification can include other
   parameters; for example, one might specify a charset parameter.

      data:text/plain;charset=iso-8859-7,%be%fg%be

   can be used for a short sequence of greek characters.

   Some applications may use the "data" URL scheme in order to provide
   setup parameters for other kinds of networking applications. For
   example, one might create a media type
           application/vnd-xxx-query

   whose content consists of a query string and a database identifier
   for the "xxx" vendor's databases. A URL of the form:

   data:application/vnd-xxx-
   query,select_vcount,fcol_from_fieldtable/local

   could then be used in a local application to launch the "helper" for
   application/vnd-xxx-query and give it the immediate data included.

5. History

   This idea was originally proposed August 1995. Some versions of the
   data URL scheme have been used in the definition of VRML, and a
   version has appeared as part of a proposal for embedded data in HTML.
   Various changes have been made, based on requests, to elide the media
   type, pack the indication of the base64 encoding more tightly, and
   eliminate "quoted printable" as an encoding since it would not easily
   yield valid URLs without additional %xx encoding, which itself is
   sufficient. The "data" URL scheme is in use in VRML, new applications
   of HTML, and various commercial products. It is being used for object
   parameters in Java and ActiveX applications.

6. Security

   Interpretation of the data within a "data" URL has the same security
   considerations as any implementation of the given media type.  An
   application should not interpret the contents of a data URL which is
   marked with a media type that has been disallowed for processing by
   the application's configuration.

   Sites which use firewall proxies to disallow the retrieval of certain
   media types (such as application script languages or types with known
   security problems) will find it difficult to screen against the
   inclusion of such types using the "data" URL scheme.  However, they
   should be aware of the threat and take whatever precautions are
   considered necessary within their domain.

   The effect of using long "data" URLs in applications is currently
   unknown; some software packages may exhibit unreasonable behavior
   when confronted with data that exceeds its allocated buffer size.

7. References

   [RFC2396] Berners-Lee, T., Fielding, R., and L. Masinter,
               "Uniform Resource Identifiers (URI): Generic Syntax", RFC
               2396, August 1998.

   [RFC1866]   Berners-Lee, T., and D. Connolly, "Hypertext Markup
               Language - 2.0.", RFC 1866, November 1995.

   [RFC2045]   Freed N., and N. Borenstein., "Multipurpose Internet Mail
               Extensions (MIME) Part One: Format of Internet Message
               Bodies", RFC 2045, November 1996.

Author contact information:

   Larry Masinter
   Xerox Palo Alto Research Center
   3333 Coyote Hill Road
   Palo Alto, CA 94304

   EMail: masinter@parc.xerox.com

Full Copyright Statement

   Copyright (C) The Internet Society (1998).  All Rights Reserved.

   This document and translations of it may be copied and furnished to
   others, and derivative works that comment on or otherwise explain it
   or assist in its implementation may be prepared, copied, published
   and distributed, in whole or in part, without restriction of any
   kind, provided that the above copyright notice and this paragraph are
   included on all such copies and derivative works.  However, this
   document itself may not be modified in any way, such as by removing
   the copyright notice or references to the Internet Society or other
   Internet organizations, except as needed for the purpose of
   developing Internet standards in which case the procedures for
   copyrights defined in the Internet Standards process must be
   followed, or as required to translate it into languages other than
   English.

   The limited permissions granted above are perpetual and will not be
   revoked by the Internet Society or its successors or assigns.

   This document and the information contained herein is provided on an
   "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
   TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
   BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
   HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Comment on RFC 2397

 

 


 

========================================================================

 

출처 : http://dean.edwards.name/weblog/2005/06/base64-ie/

Base64 Encoded Images for Internet Explorer

This is a simple trick that I’m including in the next release of IE7. Mozilla and other browsers already support Base64 encoding of images. This gives web authors the ability to express image URLs in this geeky-looking (and therefore cool) way:

<img src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////
wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML
wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="
alt="Base64 encoded image" width="150" height="150"/>

That ghastly mess will produce the following image in most decent browsers:

Base64 encoded image

Can’t wait to do it yourself now can you?

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Internet Explorer does not support Base64 encoding of images so we will take advantage of PHP’s built-in base64_decode function. We will simply pass the Base64 data back to a PHP module which will then decode the data and return the appropriate image. Now that sounds complicated doesn’t it? Here is the required PHP code:

<?php
$data = split(";", $_SERVER["REDIRECT_QUERY_STRING"]);
$type = $data[0];
$data = split(",", $data[1]);
header("Content-type: ".$type);
echo base64_decode($data[1]);
?>

That wasn’t so bad. Now we need a little bit of JavaScript to pass the Base64 data to the PHP module:

// a regular expression to test for Base64 data
var BASE64_DATA = /^data:.*;base64/i;
// path to the PHP module that will decode the encoded data
var base64Path = "/my/path/base64.php";
function fixBase64(img) {
    // check the image source
    if (BASE64_DATA.test(img.src)) {
        // pass the data to the PHP routine
        img.src = base64Path + "?" + img.src.slice(5);
    }
};
// fix images on page load
onload = function() {
    for (var i = 0; i < document.images.length; i++) {
        fixBase64(document.images[i]);
    }
};

Example: /my/base64-ie.html

In my next post I’ll show you a much sexier way of detecting and fixing the images. ;-)

 

========================================================================

 

출처 : http://dean.edwards.name/my/base64-ie.html

Base64 Encoded Images for Internet Explorer

<img src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////
wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML
wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="
alt="Base64 encoded image" width="150" height="150"/>

That ghastly mess will produce the following image:

Base64 encoded image

Explanation: /weblog/2005/06/base64-ie/

========================================================================

 

출처 : http://www.lsc.ufsc.br/~luizd/base64-to-mhtml/workaround.html

Base64  embebbed images to MHTML Format




 

This is a workaround to fix IE problem with data inline in HTML (see Specs). IE Just ignores it. Ex:

 <IMG src='data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPb
            WLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVr
            ApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KT
            kpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxM
            AF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=' width="81" height="85">

Work for most of the moderns Browsers as Mozilla, Konqueror, Opera, Safari, ... except, of course, IE.

If you see an image below, your browser is one of this.

My work arround consist on converting the HTML as an HTML Mail (MHTML) in a Multipart MIME. IE uses this to save pages as a single file. It will look ugly as plain text but the enduser won't notice it. If you are kind of lost, try to save any page with images as an single page file (.mht or .mhtml).

I used the ob_start/ob_enf_flush functions in php to capture the HTML and pass it to a function that converts all embebbed data into attachments in MHTML. It requires PEAR Mail module that I beleive is already avaiable in most of the systems.

    <?php
    
    
	function codeBase64ToMHTML ($html) {
	
		require_once 'Mail/mimePart.php';
		
		header('Content-type: message/rfc822');
		
		header('Cache-Control: no-cache');
		header('Cache-Control: no-store');
		header('Cache-Control: private');
		
		
		$reg=sql_regcase("(<(OBJECT[^>]+data=|IMG[^>]+src=))('data:[^']+'|\"data:[^\"]+\")([^>]*>)");
		
		$i=1;
		
		while (ereg ($reg, $html, $matches)) {
			// $matches[0] = All the match, ignored
			// $matches[1] = Tag until data
			// $matches[2] = Tag until data without "<", ignored
			// $matches[3] = Data part
			// $matches[4] = Remaining tag after data
		
			// Remove old tag
			$name="obj$i";
			$newTag= $matches[1]."'$name'".$matches[4];
			$html = preg_replace("/$reg/",$newTag,$html,1);
		
			if (!ereg ('[\'"]data:([^;]+);([^,]+),(.*)[\'"]',$matches[3],$dataParts))
			die ("Data format not recognized!");
		
			//$dataParts[0] = All the match, ignored
			//$dataParts[1] = Content-type
			//$dataParts[2] = Encoding
			//$dataParts[3] = Data
		
			// Decode data
			$encoding=$dataParts[2];
			switch ($encoding) {
			case 'quoted-printable':
				return quoted_printable_decode($data);
				break;
			case 'base64':
				$data=base64_decode(ereg_replace("[[:space:]]","",$dataParts[3]));
				break;
			case '8bit':
			case '7bit':
			default:
				$data=$dataParts[3];
				break;
			}
		
			$objs[$i]['content-type']= $dataParts[1];
			$objs[$i]['encoding']= $encoding;
			$objs[$i]['data']=$data;
			$objs[$i]['name']=$name;
		
			$i++;
		
			unset($matches);
			unset($dataParts);
		};
		
		
		$params['content_type'] = "Content-Type: multipart/related;\n        type=\"text/html\"";
		$email = new Mail_mimePart("", $params);
		
		$params['content_type'] = 'text/html;\n        charset="iso-8859-1"';
		$params['encoding'] = 'quoted-printable';
		
		// Encode as you wish
		// $params['encoding'] = 'base64';
		$attach =& $email->addSubPart($html, $params);
		
		$att =& $attach->encode();
		$att['headers']['Content-Location']='index.php';
		
		foreach ($objs as $obj) {
			$params['content_type'] = $obj['content-type'];
			$params['encoding']     = $obj['encoding'];
			$attach =& $email->addSubPart($obj['data'], $params);
			$att =& $attach->encode();
			$att['headers']['Content-Location']=$obj['name'];
		}
		
		$beforeHeaders[]='From: ';
		$beforeHeaders[]='Subject: Teste';
		$beforeHeaders[]='Date: '.date("D, d M Y H:i:s O");
		$beforeHeaders[]='Mime-Version: 1.0';
		
		$afterHeaders[]='';
		$afterHeaders[]='This is a multi-part message in MIME format.';
		$afterHeaders[]='';
		
		$msg = $email->encode();
		$msg['headers']=array_merge($beforeHeaders,$msg['headers'],$afterHeaders);
		
		return join("\n",$msg['headers'])."\n".$msg['body'];
	}

    
    	// Detect this "sweet" browser
        if (eregi("MSIE",$_SERVER['HTTP_USER_AGENT']))
    		$MHTML=true;

	// Do what is needed to do	
	if ($MHTML)
    		ob_start("codeBase64ToMHTML");    
    ?>
    <HTML>
    <HEADER>
    	<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
	<META HTTP-EQUIV="EXPIRES" CONTENT="0">
	<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
    </HEADER>
    
    <BODY>
    	...
	<IMG src='data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPb
            WLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVr
            ApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KT
            kpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxM
            AF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=' width="81" height="85">	
    </BODY>
    </HTML>	    
    <?php
    
	// End this stuff	
	if ($MHTML)
    		ob_end_flush();
    ?>
    

And... that's it! It really work. Of couse, there is some problems.

  • Dynamic pages that its URL isn't changed aren't updated. IE keeps loading from cache;
  • Special characters in URL (ex: "[","]") for GET requests are translated and if needed, won't work in the second request;
  • Problems, they are always everywhere...

If you found a new problem or a new solution, PLEASE, email me: luizluca using g mail.com . I'll anwser emails in English and Portuguese.

[출처] http://gnujava.com/board/article_view.jsp?article_no=2740&board_no=3&table_cd=EPAR01&table_no=01

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
658 인공지능이 의식을 가질 수 있는가 file 졸리운_곰 2018.03.07 96
657 당근마켓에서 딥러닝 활용하기 - 불량 게시물 검사 file 졸리운_곰 2018.03.06 130
656 머신러닝 단기집중과정 by google 졸리운_곰 2018.03.04 89
655 한글 형태소 분석의 이해 NLP file 졸리운_곰 2018.03.04 83
654 루아 알고리즘 라이브러리 lua-algorithms stack queue tree file 졸리운_곰 2018.03.03 1385
653 VB.NET 알고리즘 구현 - Stack, Queue Data Type file 졸리운_곰 2018.02.27 310
652 TopCoder 사용 방법 (탑코더 시작하기) file 졸리운_곰 2018.02.26 360
651 MXNet을 활용한 이미지 분류 앱 개발하기 file 졸리운_곰 2018.02.25 118
650 [Artificial Intelligence / MXNet] MXNet을 이용한 Classification 문제 풀기 file 졸리운_곰 2018.02.25 66
649 [Artificial Intelligence / MXNet] Windows 환경에 MXNet 설치하기 file 졸리운_곰 2018.02.25 93
648 [Artificial Intelligence / MXNet] MXNet 소개 file 졸리운_곰 2018.02.25 98
647 Blender 단축키 file 졸리운_곰 2018.02.25 156
646 Blender 단축키 정리 모음 file 졸리운_곰 2018.02.25 164
645 [자바스크립트] 선택한 이미지 base64 코드로 변환하여 화면에 보여주기 file 졸리운_곰 2018.02.21 253
644 [제목] 한번의 커넥션으로 이미지 모두 전송하는 방법 졸리운_곰 2018.02.21 101
643 data URIs로 image 생성하기 file 졸리운_곰 2018.02.21 92
642 Base64 이미지 사용하기 file 졸리운_곰 2018.02.21 111
641 html img , a에 직접 이미지, 파일 데이터 넣기 졸리운_곰 2018.02.21 110
» BASE64 로 인코딩 한 이미지 data를 직접 HTML 문서에 추가하는 방법 외 file 졸리운_곰 2018.02.21 296
639 Torch7 따라 해 보기 file 졸리운_곰 2018.02.19 88
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED