Java

Base64 인코딩된 이미지 데이터 파일로 저장

심나라 2022. 5. 26. 13:50
728x90

자바에서 html 파싱을 할 수 있도록 도와주는 라이브러리 Jsoup을 이용해서 Base64 인코딩된 이미지를 파일로 저장하는 소스 입니다. 먼저 jsoup.jar 파일을 다운로드 받아서 자바프로젝트에 추가 해 줍니다. 

 

Base64ImgFileSave.java

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import Utils.DateUtil;
import Utils.FileUtil;
import domain.UploadFile;

public class Base64ImgFileSave {
	
	public static void main(String[] args) {
		
		String sveFilePath = "D:/temp";
		String base64EncodingData = "<p><img src=\"data:image/png;base64,Base64 인코딩된 데이터" style=\"width: 414px;\" data-filename=\"img1.PNG\"><br></p>";
		
		// Base64 인코딩 데이터 로컬에 저장
		base64ImgLocalSave(sveFilePath, base64EncodingData);
		
	}
	
	/**
	 * Base64 인코딩된 이미지 데이터 로컬에 저장 
	 * @param dir 저장할 디렉토리 경로
	 * @param content base64 인코딩 이미지 데이터
	 */
	public static boolean base64ImgLocalSave(String dir, String content) {
		
		if(content.indexOf("data:image/") < 0) return false;
		
		// 문서 객체 생성
		Document doc = Jsoup.parse(content);
		// img 태그 src 속성의 값만 가져옴
		Elements elements = doc.select("img[src]");

		for(Element item : elements) {
			String imageSource = item.attr("src").toString();

			if(imageSource.indexOf("data:image/") < 0) {
				continue;
			}
			
			// 문서 객체에서 파일명 생성
			String originalName = item.attr("data-filename").toString();

			// 파일 생성
			UploadFile uploadFile = imageLocalSave(imageSource, dir, originalName);
			System.out.println("uploadFile : " + uploadFile.toString());
		}

		return true;
	}
	
	public static UploadFile imageLocalSave(String imageSource, String dir, String originalName) {
		
		if(imageSource.indexOf("data:image/") < 0) {
			return null;
		}
		
		String[] imageSourceArr = imageSource.split(",");
		if(imageSourceArr.length != 2) {
			return null;
		}
		
		// 이미지 데이터 저장
		byte imageBytes[] = Base64.decodeBase64(imageSourceArr[1]);
		ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
		
		// 업로드 디렉토리 생성
		String uploadDir = dir + "/" + DateUtil.getFormattedTime(new Date(), "yyyy/MM/dd") + "/";
		FileUtil.createDir(uploadDir);
		
		// 신규 파일명
		String newFilename = DateUtil.getFormattedTime(new Date(), "yyyyMMddHHmmss") + originalName.substring(originalName.lastIndexOf("."));
		
		// 파일생성
		try {
			Files.copy(bis, Paths.get(uploadDir).resolve(newFileName));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try { bis.close(); } catch (Exception e) {} 
		}
		
		// 파일 사이즈
		long fileSize = FileUtil.getFileSize(uploadDir, newFileName);
		
		// 파일정보
		UploadFile uploadFile = new UploadFile(originalName, newFileName, uploadDir, fileSize);

		return uploadFile;
	}
	
}

 

UploadFile.java

import lombok.Data;

@Data
public class UploadFile {

	private String originalName;
	private String newName;
	private String fullPath;
	private long fileSize;
	
	public UploadFile(String originalName, String newName, String fullPath, long fileSize) {
		super();
		this.originalName 	= originalName;
		this.newName 		= newName;
		this.fullPath 		= fullPath;
		this.fileSize		= fileSize;
	}
	
}

 

DataUtil.java

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
	
	/**
	 * Date 값을 주어진 Date Pattern 으로 변환하여 반환한다.
	 * @param date 변환하고자 하는 날짜의 Date 값
	 * @param datePattern 날짜 포맷
	 * @return
	 */
	public static String getFormattedTime(Date date, String datePattern) {
		SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
		return formatter.format(date);
	}

}

 

FileUtil.java

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

public class FileUtil {

	/**
	 * 디렉토리가 존재하지 않으면 생성함. (하위디렉토리 생성)
	 * @param dir 디렉토리 경로
	 */
	public static void createDir(String dir) {
        Path path = Paths.get(dir);
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
    /**
     * 파일 사이즈(byte) 구하기
     * @param filePath 디렉토리 경로
     * @param fileName 파일명
     * @return
     */
    public static long getFileSize(String filePath, String fileName) {
        long fileSize = 0;

        if (StringUtils.isNotBlank(fileName)) {
            File file = new File(Paths.get(filePath).resolve(fileName).toString());
            if (file.exists() && file.isFile()) {
                fileSize = file.length();
            }
        }
        return fileSize;
    }
    
}

 

사용되는 라이브러리.

728x90