민서네집

MyBatis를 이용해서 이미지 파일을 DB에 저장하고 불러오기 본문

Java

MyBatis를 이용해서 이미지 파일을 DB에 저장하고 불러오기

브라이언7 2015. 4. 20. 16:01

MyBatis 버전: 3.2.7

MySQL 버전: 5.6.20-log

OS: Windows 7


Word 문서를 parsing 해서 이미지 파일을 추출해서 Database에 넣고 싶었다.


이미지를 byte[] 의 형태로 빼올 수 있는데, MySQL 의 BLOB Data Type 컬럼에 


byte[] 데이터를 그냥 Map<String,Object> 에 넣어서 insert 해 주면 BLOB 컬럼에 그냥 들어간다.


Java 에서 byte Array 를 blob Data Type 으로 변환해 주는 방법이 있기는 한데, MyBatis 에서 자동으로 되는 것 같다.

이렇게 하나 변환을 안해 주나 결과가 같았다.


How to convert byte array to blob

http://stackoverflow.com/questions/10849893/how-to-convert-byte-array-to-blob


Blob blob = new javax.sql.rowset.serial.SerialBlob(bytes);


HeidiSQL Tool 에서, 데이터가 들어있는 BLOB 컬럼을 더블 클릭해서 내용을 보니, 235 bytes 밖에 표시가 안 되서, 뭔가 잘못 들어간 줄 알았더니,


SELECT LENGTH({BLOB 컬럼 이름}) FROM {테이블 이름} 해서 데이터의 길이를 측정해 봤더니, 이미지 파일의 크기 만큼 제대로 들어가 있었다.


Data를 빼 올 때도 Map<String, Object> 형태로 반환 받아서, MAP 의 get() 으로 꺼내와서 byte[] 로 형변환하면 그대로 꺼내와진다. 그래서 이미지로 저장할 수도 있다.


private static void saveImage(byte[] bytes, String fileName) {

	BufferedImage image = null;
	try {
		image = ImageIO.read(new ByteArrayInputStream(bytes));
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	String filePath = "D:\\temp\\";
	File outputfile = new File(filePath + fileName);

	String extension = fileName.substring(fileName.lastIndexOf('.')+1);

	try {
		ImageIO.write(image, extension, outputfile);
	} catch (IOException e) {
		e.printStackTrace();
	}
}


참고적으로 hexString 으로 저장된 문자열을 byte[] 로 바꾸는 코딩은 다음과 같다.

아래 코드에서 png 파일의 모든 이미지 데이터를 String 으로 만든 것이 아니라 앞 부분만 잘라 놓은 것이라서 이미지 파일이 만들어지지는 않는다.


public static void main(String[] args) { ArrayList<Byte> byteList = new ArrayList<Byte>(); String string = "89504E470D0A1A0A0000000D49484452000004560000013F02000000203F000000000173524742003F1C3F0000000467414D410000B18F0B3F0500000009704859730000171100001711013F3F0000657449444154785EEDDD79A04C3FC0F1BBB83F84643F3F212D5289423FA9944A3F4AF5D3373F642D51A1A83F3F49423F5BF6EC3FB9DC7B3F667E3F3F4D771973673F79C6BC5F7F709E673F673F96E73F3F4887C31101000000003F4A3F000000006180140800000040182105020000001046483F000000003F522000000000613F080000004018210502000008312929293F3F"; for(int i=0; i<string.length(); i=i+2) { int parseInt = Integer.parseInt(string.substring(i, i+2), 16); byteList.add((byte)parseInt); } Byte[] byteObjects = byteList.toArray(new Byte[byteList.size()]); byte[] bytes = new byte[byteObjects.length]; int i=0; for(byte b: byteObjects) bytes[i++] = b; saveImage(bytes, "temp.png"); }


[참고]

java에서 hexString 을 int로 변환 ( hexString to int )



Spring3 MVC와 MyBatis를 이용하여 이미지를 BLOB 타입으로 DB 저장 및 출력해보기


http://hellogk.tistory.com/129


how to convert byte[] to Byte[], and the other way around?


Get Image from the document using Apache POI


Comments