Step-by-Step

[Spring] 10. DB에 이미지 저장 - BLOB (+ Python에서 열기) 본문

프로젝트/Eggo (Mobile App)

[Spring] 10. DB에 이미지 저장 - BLOB (+ Python에서 열기)

희주(KHJ) 2022. 5. 21. 02:45

앱을 통해 사용자가 문서를 촬영하면 Python에서 문서를 스캔한 값을 돌려줘야 한다

 

근데 현재 Android / Spring / Python 각각 다른 팀원이 구현중이다!

그럼 우선 파일을 직접. DB에 저장해야 하는데, BLOB형태로 많이 저장하는 것 같다.

 

BLOB 

- Binary Large Object (바이너리 라지 오브젝트)

- 데이터베이스 관리 시스템의 하나의 엔티티로 저장되는 이진 데이터의 모임

- 크기에 따라 여러 종류가 있음 

- TINY BLOB : 255 bytes
- BLOB : 65535 bytes (64KB)
- MEDIUMBLOB : 16777215 bytes (16MB)
- LONGBLOB : 62994967295 bytes (4GB)

참조 : https://tableplus.com/blog/2019/10/tinyblob-blob-mediumblob-longblob.html

 

따라서 데이터베이스에 저장되는 부분도 BLOB로 설정해야 한다

DB 설정

우선 이런식으로 설정해주었고, 아직 테스트기 때문에 따로 KEY값은 주지 않았다

처음에는 크기 안보고 그냥 BLOB로 했다가 용량이 안돼서 LONGBLOB 로 설정했다

 

 

[Spring - Controller]

	@PostMapping("/scanPhoto")
	public @ResponseBody Map<String, Object> getPhoto(@RequestParam("file") MultipartFile file) throws IOException {
		System.out.println("이미지 스캔 요청");
		
		System.out.println(file.getName());		//파일 파라미터 이름
		System.out.println(file.getSize());		//파일 사이즈
		System.out.println(file.getOriginalFilename());	//파일 실제 이름
		byte[] data = file.getBytes();			//파일 실제 내용
		
		Map<String, Object> param = new HashMap<String, Object>();
		//Convert to Blob
		try {
			Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
			param.put("file", blob);
			param.put("file_name", file.getOriginalFilename());
			param.put("file_size",file.getSize());
			photoAIService.insertPhoto(param);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}

- MultipartsFile로 받아서 BLOB로 변경시켜준 다음에 DB로 전달한다

- 파일을 byte[] 배열에 담아서 javax.sql.rowset.serial.SerialBlob 이용해서 Blob 객체에 저장한다

 

 

[Jupyter - Python]

import pymysql			// DB 연결용
import PIL			// Image로 전환
from PIL import Image
import io			// byte 받아옴

- 필요한 라이브러리를 추가해준다

 

 

db_Conn = pymysql.connect("--DB 정보--")	// user, password, host, db, charset 설정
db_cursor = db_Conn.cursor()		
sql = 'SELECT * FROM photo'				
db_cursor.execute(sql)
data = db_cursor.fetchall()				// DB 정보를 받아 data에 저장

- DB랑 연결해서 data를 가져온다

 

 

data_io = io.BytesIO(data[0][0])
img = Image.open(data_io)

- bytes로된 값을 가져온 후, image로 바꿔주면 완료!

 

Comments