JAVA - Binary Code Encode Decode (Binary <-> PNG )

김상혁·2021년 4월 30일
0

기능 모아두기

목록 보기
1/6
// 여러 MSA 서비스 안에서 RestAPI로 이미지 파일을 전송할 때 사용

RestApi를 통해 이미지 파일 등을 Json에 넣어 보낼 경우

파일 -> BinaryCode
BinaryCode -> String

       (전송)

String -> BinaryCode
BinaryCode -> 파일

위 절차로 보낼 수 있다.

바이너리 코드는 Base64를 사용해 인코드, 디코드해야한다.

String temp = new String(binaryCode);
byte[] byteArray = temp.getBytes();

위와 같이 할 경우 binaryCode와 byteArray의 값이 달라 문제가 된다.

// 파일 -> 바이너리코드
//(file.type == MultipartFile)
bytes = file.getBytes();
// 바이너리코드 -> 스트링
import java.util.Base64;
String temp = Base64.getEncoder().encodeToString(binaryCode);
// 스트링 -> 바이너리코드
import java.util.Base64;
byte[] binary = Base64.getDecoder().decode(temp);
// 바이너리코드 -> 파일
FileInputStream inputStream = new FileInputStream(uploadPath + fileName);

BufferedImage bufferedImage = ImageIO.read(inputStream);
File file = new File(filePath_image);
ImageIO.write(bufferedImage, "png", file);

inputStream.close();

0개의 댓글