본문 바로가기

카테고리 없음

[Java] 모바일에서 촬영 된 사진이 회전이 되어서 저장이 돼요.

반응형

문제코드

	public String convertBinary(MultipartFile files) throws Exception{
		String fileName = StringUtils.cleanPath(Objects.requireNonNull(files.getOriginalFilename())) ;
		BufferedImage image = ImageIO.read(files.getInputStream());
		//ImageBuffer Null Check
		if (image == null) {
			throw new IllegalArgumentException("Invalid image file.");
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(image, fileName.substring(fileName.lastIndexOf(".") + 1), baos);
		return new String(Base64.encodeBase64(baos.toByteArray(), false));
	}
  • ImageIo.read()를 이용해 ImageInputStream 을 생성후에 BufferedImage 생성 시에 meta 정보인 Exif을 인식하지 못하므로
    생성되는 Base64데이터를 디코딩 후 파일저장 시 회전 된 이미지를 만나볼수 있음

대안법

  • ImageIO를 사용해야된다면...

ImageIO.read() 사용 시 모바일 이미지 파일 내부에 있는 메타정보인 Exif정보를 읽을 수 없음.

https://stackoverflow.com/questions/15978809/imageio-read-always-rotates-my-uploaded-picture

해당 솔루션 대로 원본 이미지대로 회전 진행

 

  • ImageIO를 사용하지 않는다면..
	public String convertBinary(MultipartFile files) throws Exception{
		// return Base64.getEncoder().encodeToString(files.getBytes());
		String fileName = StringUtils.cleanPath(Objects.requireNonNull(files.getOriginalFilename()));
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		files.getInputStream().transferTo(baos);  // 원본 이미지 바이너리 데이터를 직접 Base64로 변환
		String encData = Base64.getEncoder().encodeToString(baos.toByteArray());
		baos.close();
		return encData;
	}

ImageIo 미사용으로 정상적인 이미지 데이터를 만나볼수 있음

반응형