ImageMagickUtils.java 6.7 KB
package com.framework.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ImageMagickUtils {
	private static Log log = LogFactory.getLog(ImageMagickUtils.class);

	private static final String MAGICK_DIRECTORY = PropertiesLoader.get("MAGICK_DIRECTORY", "/application.properties");

	private static final String MAGICK_FILE = PropertiesLoader.get("MAGICK_FILE", "/application.properties");

	private static final String IMAGE_CONFIG = PropertiesLoader.get("IMAGE_SIZE", "/application.properties");

	public static Boolean resize(File ori) {
		try {
			log.info("MAGICK_FILE::::" + MAGICK_FILE);

			int[][] whs = getImageSizeConfig();
			String pathPicFrom = ori.getAbsolutePath();
			log.info("pathPicFrom===============" + pathPicFrom);
			try {
				javax.imageio.ImageIO.read(ori);
			} catch (Exception e) {
				convertCYMK(pathPicFrom);
			}

			convertOrient(pathPicFrom);

			String sizeStr = getImageSize(pathPicFrom);
			log.info("sizeStr===============" + sizeStr);

			if (StringUtils.isNotEmpty(sizeStr)) {
				String[] wh = sizeStr.split("x");
				log.info(wh[0] + "===============wh===================" + wh[1]);
				int imageWideth = Integer.parseInt(wh[0]);
				int imageHeight = Integer.parseInt(wh[1]);

				for (int i = 0; i < whs.length; i++) {
					int changeToWideth = whs[i][0];
					int changeToHeight = whs[i][1];

					if (imageWideth <= changeToWideth && imageHeight <= changeToHeight) {
						File to = FileUtils.genOutFile(ori, changeToWideth, changeToHeight);
						FileUtils.copyFile(ori, to);
					} else {
						File saveFile = FileUtils.genOutFile(ori, changeToWideth, changeToHeight);
						int[] outwh = new int[2];
						if (imageWideth >= imageHeight) {
							outwh[0] = changeToWideth;
							outwh[1] = (int) (1.0 * imageHeight / imageWideth * changeToWideth);
						} else {
							outwh[0] = (int) (imageWideth * changeToHeight / imageHeight * 1.0);
							outwh[1] = changeToHeight;
						}

						// 修正開始轉換圖檔
						// 改用bat檔直接執行convert指令
						String pathPicTo = saveFile.getAbsolutePath();
						log.info("pathPicTo===============" + pathPicTo);
						convertPic(pathPicFrom, outwh, pathPicTo);
					}
				}
			}
		} catch (IOException ioe) {
			log.error("File " + ori.getAbsolutePath() + " io error!!!", ioe);
			return false;
		}
		return true;
	}

	private static String getImageSize(String source) throws IOException {
		List<String> parameterList = new ArrayList<String>();
		if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
			parameterList.add(MAGICK_FILE);
		}
		parameterList.add("identify");
		parameterList.add("-format");
		parameterList.add("%wx%h");
		parameterList.add(source);
		log.info("getImageSize parameterList======" + parameterList);
		ProcessBuilder processBuilder = new ProcessBuilder(parameterList);
		processBuilder.redirectErrorStream(true);
		if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
			processBuilder.directory(new File(MAGICK_DIRECTORY));
		}
		Process process = processBuilder.start();
		// Read out dir output
		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String imageSize = br.readLine();
		return imageSize.startsWith("identify") ? null : imageSize;
	}

	private static void convertPic(String pathPicFrom, int[] outwh, String pathPicTo) throws IOException {
		if (!new File(pathPicTo).exists()) {
			List<String> parameterList = new ArrayList<String>();
			if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
				parameterList.add(MAGICK_FILE);
			}
			parameterList.add("convert");
			parameterList.add("-resize");
			parameterList.add(String.valueOf(outwh[0]) + "x" + String.valueOf(outwh[1]));
			parameterList.add("-antialias");
			parameterList.add(pathPicFrom);
			parameterList.add(pathPicTo);
			log.info("convertPic parameterList======" + parameterList);
			ProcessBuilder processBuilder = new ProcessBuilder(parameterList);
			processBuilder.redirectErrorStream(true);
			if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
				processBuilder.directory(new File(MAGICK_DIRECTORY));
			}
			waitForProcess(processBuilder.start());
		}
	}

	private static void convertCYMK(String pathPicFrom) throws IOException {
		List<String> parameterList = new ArrayList<String>();
		if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
			parameterList.add(MAGICK_FILE);
		}
		parameterList.add("mogrify");
		parameterList.add("-colorspace");
		parameterList.add("RGB");
		parameterList.add("-quality");
		parameterList.add("80");
		parameterList.add(pathPicFrom);
		log.info("convertCYMK parameterList======" + parameterList);
		ProcessBuilder processBuilder = new ProcessBuilder(parameterList);
		processBuilder.redirectErrorStream(true);
		if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
			processBuilder.directory(new File(MAGICK_DIRECTORY));
		}
		waitForProcess(processBuilder.start());
	}

	private static void convertOrient(String pathPicFrom) throws IOException {
		List<String> parameterList = new ArrayList<String>();
		if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
			parameterList.add(MAGICK_FILE);
		}
		parameterList.add("convert");
		parameterList.add(pathPicFrom);
		parameterList.add("-auto-orient");
		parameterList.add(pathPicFrom);
		log.info("convertOrient parameterList======" + parameterList);
		ProcessBuilder processBuilder = new ProcessBuilder(parameterList);
		processBuilder.redirectErrorStream(true);
		if (StringUtils.isNotEmpty(MAGICK_DIRECTORY)) {
			processBuilder.directory(new File(MAGICK_DIRECTORY));
		}
		waitForProcess(processBuilder.start());
	}

	private static void waitForProcess(Process process) throws IOException {
		// Read out dir output
		InputStream is = process.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String line;

		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}
	}

	private static int[][] getImageSizeConfig() {
		int[][] result;
		String[] p = IMAGE_CONFIG.split(";");
		result = new int[p.length][2];
		for (int i = 0; i < p.length; i++) {
			String m = p[i];
			m = m.replace("[", "");
			m = m.replace("]", "");
			String[] y = m.split(",");
			result[i][0] = Integer.parseInt(y[1].replace("\"", ""));
			result[i][1] = Integer.parseInt(y[2].replace("\"", ""));
		}
		return result;
	}
}