본문 바로가기
프로그래밍 언어/java + jsp + jstl

[Java/jsp] 자바로 이미지를 base64 인코딩 소스로 변환하는 함수

by 우림 2015. 12. 26.

자바로 이미지를 base64 인코딩 소스로 변환하는 함수입니다.

필요하실 때 참고하세요.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static String getBase64String( String[] imageUrl, String content ) throws Exception{
 
    if( imageUrl.length > 0 )
    {
        int imageUrlLength = imageUrl.length;
        String[] imageString = new String[ imageUrlLength ];
 
        forint i = 0; i < imageUrlLength; i++ )
        {
            String filePathName = imageUrl[i].replace(“file:///”, “”);
            String fileExtName = filePathName.substring( filePathName.lastIndexOf(“.”) + 1);
 
            FileInputStream inputStream = null;
            ByteArrayOutputStream byteOutStream = null;
 
            try
            {
                File file = new File( filePathName );
 
                if( file.exists() )
                {
                    inputStream = new FileInputStream( file );
                    byteOutStream = new ByteArrayOutputStream();
 
                    int len = 0;
                    byte[] buf = new byte[1024];
                    while( (len = inputStream.read( buf )) != -1 ) {
                        byteOutStream.write(buf, 0, len);
                    }
 
                    byte[] fileArray = byteOutStream.toByteArray();
                    imageString[i] = new String( Base64.encodeBase64( fileArray ) );
 
                    String changeString = “data:image/+ fileExtName +”;base64, “+ imageString[i];
                    content = content.replace(imageUrl[i], changeString);
                }
            }
            catch( IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                inputStream.close();
                byteOutStream.close();
            }
        }
    }
 
    return content;
}
cs


위 소스에서 아래 그림이 base64로 변환하는 부분입니다.


이렇게 변환된 소스를 아래처럼 HTML 태그에 입력하시면 이미지가 화면에 나타납니다.

<img src=”https://t1.daumcdn.net/cfile/tistory/2338383656E718EE1F"color: rgb(34, 116, 28);">/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAoHBwkHBgoJCAkLCwoMDxkQDw4ODx4WFxIZJCAmJSMgIyIoLTkwKCo2KyIjMkQyNjs9QEBAJjBGS0U+Sjk/QD3/2wBDAQsLCw8NDx0QEB09KSMpPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT3/wAARCADjAZcDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4…” />






댓글