프로그래밍언어/Java
ByteArray를 이미지 파일로 저장하는 방법
D.Y
2016. 2. 28. 16:30
반응형
이미지 파일을 ByteArray로 변환 하는 방법과 ByteArray를 이미지파일로 저장하는 방법에 대해서 알아보겠습니다.
서버와 클라이언트 혹은 서버와 서버간의 통신에서 이미지 파일을 전송 및 수신을 해야 할때가 있습니다.
이때, ByteArrayStream을 사용하여 이미지 파일을 전송하고 수신해서 다시 이미지 파일로 저장 할 수 있습니다.
(스트림 : 데이터를 운반하는데 사용되는 연결 통로)
예제 코드를 통해 알아보도록 하겠습니다.
메소드 단위 sample code
- input : 이미지파일 경로, output : byteArray(byte[])
(이미지 파일을 바이트 배열로 저장)
public byte[] imageFileConvertToByteArray(String imageFilePath) throws Exception
{
File file = new File(imageFilePath);
BufferedImage bufferedImage = ImageIO.read(file);
ImageIO.write(bufferedImage, "png", bufferedImage);
bufferedImage.flush();
byte[] imageByte = bufferedImage.toByteArray();
bufferedImage.close();
return imageByte;
}
- input : byteArray(byte[]), output : 이미지파일 저장
(바이트 배열을 이미지 파일로 저장)
public void byteArrayConvertToImageFile(byte[] imageByte) throws Excetion
{
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageByte);
BufferedImage bufferedImage = new ImageIO.read(inputStream);
ImageIO.write(bufferedImage, "png", new File("/var/opt/image.png")); //저장하고자 하는 파일 경로를 입력합니다.
}
jdk 7 부터는 File을 ByteArray로 손쉽게 변환 할 수 있습니다.
- byte[] fileByteArray = Files.readAllBytes("파일의 절대경로");
반응형