[JSP] DB의 BLOB 타입으로 저장된 이미지를 출력해 보자.

2012. 4. 4. 13:47개발관련기록/Servlet_JSP

반응형







파일 이미지를 다루는 방식은 인터넷에 많은데
이번에 Byte[]로 받아 처리하는 방식에 대해 정리 차원에서 기록해보자.


ibatis에서 BLOB 타입을 받아 처리하려면 설정해주어야 할 문제가 있다.
(자세한 사항은 http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/Ibatisclobblob  ,
http://blog.naver.com/PostView.nhn?blogId=mispro97&logNo=20053634922 
참고) 






1. applicationContext.xml 소스 추가

접기


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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
                           http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">

<!--
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <property name="url" value="jdbc:hsqldb:mem:."/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
    </bean>
<!--
    <bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://dbhost-prospring-psql/prospring"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
-->
    <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
        <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/>
    </bean>

    <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>


</beans>
Pastie #2235826 linked directly from Pastie.

접기




이렇게 applicationContext.xml 파일에 추가해주어야 ibatis에서 BLOB 타입을 처리해준다고 한다.
(역시, 위의 링크와 동일하게 자세한 사항은 http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/Ibatisclobblob , 
http://www.java2s.com/Code/Java/Spring/SetupDataSourceforMySQL.htm  
참고) 





2. 이미지를 byte[]로 받아 출력해 보자

접기


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
@RequestMapping("/ShowImage")
public void showImage( @RequestParam("imgIdx") String imgIdx
                      ,HttpServletResponse response
                      ,HttpServletRequest request) throws Exception  {
    
    InputStream is = null;
    byte[] bytes;
    
    /* 저는 jpg 파일로 고정이라 이렇게 했지만 여러분은 타입을 얻어와야 한다. */
    String content_type = "image/jpeg";
    response.setContentType(content_type);  // Content Type Set
    
    /* DB의 BLOB 타입의 내용을 가져와서 bytes 변수에 담아보자. */
    Master master = new Master();
    master = MasterMgr.getMasterImg(imgIdx);
    bytes = master.getBlobTypeImage();

    /* String --> InputStream 타입으로 변환 */
    is = new ByteArrayInputStream(bytes);
    
    
    /* 이제 OutputStream 으로 출력해보자*/
    ServletOutputStream os = response.getOutputStream();
    
    int binaryRead;
    
    while ((binaryRead = is.read()) != -1)	{
        os.write(binaryRead);
    }
    
}
Pastie #2235868 linked directly from Pastie.

접기







3. 이미지를 Resize해서 출력해 보자
( 출처 : http://blog.naver.com/PostView.nhn?blogId=ppant&logNo=70107766793 )

접기


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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
@RequestMapping("/ShowImage")
public void showImage( @RequestParam("imgIdx") String imgIdx
                      ,HttpServletResponse response
                      ,HttpServletRequest request) throws Exception  {
    
    InputStream is = null;
    byte[] bytes;
    
    /* 저는 jpg 파일로 고정이라 이렇게 했지만 여러분은 타입을 얻어와야 한다. */
    String content_type = "image/jpeg";
    response.setContentType(content_type);  // Content Type Set
    
    /* DB의 BLOB 타입의 내용을 가져와서 bytes 변수에 담아보자. */
    Master master = new Master();
    master = MasterMgr.getMasterImg(imgIdx);
    bytes = master.getBlobTypeImage();

    /* String --> InputStream 타입으로 변환 및 가로:100px, 비율:1 에 맞추어 Resize */
    is = new ByteArrayInputStream(generateImage(bytes, 100, 1));
    
    
    /* 이제 OutputStream 으로 출력해보자*/
    ServletOutputStream os = response.getOutputStream();
    
    int binaryRead;
    
    while ((binaryRead = is.read()) != -1)	{
        os.write(binaryRead);
    }
    
}


public static byte[] generateImage( byte[] imageContent
                                   ,int maxWidth
                                   ,double xyRatio) throws IOException {
                                   
    BufferedImage originalImg = ImageIO.read( new ByteArrayInputStream(imageContent));

    //get the center point for crop
    int[] centerPoint = { originalImg.getWidth() /2, originalImg.getHeight() / 2 };

    //calculate crop area
    int cropWidth=originalImg.getWidth();
    int cropHeight=originalImg.getHeight();

    if( cropHeight > cropWidth * xyRatio ) {
        //long image
        cropHeight = (int) (cropWidth * xyRatio);
    } else {
        //wide image
        cropWidth = (int) ( (float) cropHeight / xyRatio) ;
    }

    //set target image size
    int targetWidth = cropWidth;
    int targetHeight = cropHeight;

    if( targetWidth > maxWidth) {
        //too big image
        targetWidth = maxWidth;
        targetHeight = (int) (targetWidth * xyRatio);
    }

    //processing image
    BufferedImage targetImage = new BufferedImage( targetWidth
                                                  ,targetHeight
                                                  ,BufferedImage.TYPE_INT_RGB);
                                                  
    Graphics2D graphics2D = targetImage.createGraphics();
    graphics2D.setBackground(Color.WHITE);
    graphics2D.setPaint(Color.WHITE);
    graphics2D.fillRect(0, 0, targetWidth, targetHeight);
    graphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION
                                ,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage( originalImg, 0, 0
                         ,targetWidth, targetHeight
                         ,centerPoint[0] - (int)(cropWidth /2)
                         ,centerPoint[1] - (int)(cropHeight /2)
                         ,centerPoint[0] + (int)(cropWidth /2)
                         ,centerPoint[1] + (int)(cropHeight /2)
                         ,null);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageIO.write(targetImage, "png", output);

    return output.toByteArray();
}
Pastie #2235897 linked directly from Pastie.

접기








4. 화면 출력


<img src="/ShowImage.do?imgIdx=007 />


이제 화면에 이미지가 보이나요? ㅋㅋㅋ


출처 : http://blog.kimkoon.net/1007

반응형