1. 程式人生 > >oss圖片處理例項

oss圖片處理例項

最近用到阿里雲的oss儲存圖片資料,並且使用了圖片處理功能,發現相關的技術文件都沒有例項提供,我就把程式碼奉獻出來嘍。

主要的Control類

package com.zufangbao.earth.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zufangbao.earth.util.ExceptionUtils;
import com.zufangbao.earth.util.UploadUtil;
import com.zufangbao.earth.web.controller.ImageControllerSpec.I_Get_Image_Key;
import com.zufangbao.gluon.spec.earth.MessageTable4Earth;

/**
 * @author Xiepf
 * 2015年12月21日
 */
@Controller
@RequestMapping(ImageControllerSpec.NAME)
public class ImageController {
		@Autowired
		private UploadUtil uploadUtil;
		
		private static final Log logger = LogFactory.getLog(ImageController.class);
		
		@RequestMapping(value = I_Get_Image_Key.NAME, method = RequestMethod.POST)
		public HashMap<String, String> uploadImage(HttpServletRequest request, HashMap<String , Integer> parameters) {
			
			FileOutputStream fos = null;
			
			HashMap<String, String> urlMap = new HashMap<String, String>();
			
			try {
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				MultipartFile multipartFile = multipartRequest.getFile(I_Get_Image_Key.PARAM_IMAGE);
				String key = multipartFile.getContentType();
				
				Boolean isAllowType = IsAllowType(key);
				if(!isAllowType){
					logger.error("#uploadImage occur error, FileType is not allow!");
					return null;
				}
				
				if(parameters.containsKey("width")==false && parameters.containsKey("hight")){
					logger.error("#uploadImage occur error, width and hight should have one least!");
					return null;
				}
				
				byte[] arr = multipartFile.getBytes();
				
				String targetPath = getTargetPath();
				File imageFile = new File(targetPath);
				fos = new FileOutputStream(imageFile);
				try {
					fos.write(arr);
				} finally {
					if(null != fos){
						fos.close();
					}
				}
				
				UploadUtil.uploadImage(targetPath);
				
				urlMap.put("original", UploadUtil.getAliYunUrl()+getFileName());

				urlMap.put("thumbnail", uploadUtil.getThumbnail(getFileName(),parameters));
				
//System.out.println(urlMap);
				return urlMap;
			} catch (Exception e) {
				int errCode = ExceptionUtils.getErrorCodeFromException(e);
				
				String message = MessageTable4Earth.getMessage(errCode);
				
				logger.error("#uploadImage occur error, code[" + errCode +" ],message["+message+"]", e.fillInStackTrace());
				
				return null;
			}
		}

//判斷圖片格式是否合法
		public Boolean IsAllowType(String key) {
			String fileType = key.split("/")[1];
			String[] formats = {"jpg","png","webp","bmp","jpeg"};
			List<String> allowFormats = Arrays.asList(formats);
			if(allowFormats.contains(fileType.toLowerCase()))return true;
			else return false;
		}
		
		@Value("#{config['IMG_ROOT_PATH']}")
		private String IMG_ROOT_PATH = "/temp";
		private String imgUUID;
		public String getTargetPath() {
			imgUUID = UUID.randomUUID().toString();
			String path = IMG_ROOT_PATH + format(getNowTimestamp(), I_Get_Image_Key.DEFAULT_DATE_PATTERN)+ "/";
			File file =new File(path);    
			//如果資料夾不存在則建立    
			if  (!file .exists()  && !file .isDirectory()) {       
			    file .mkdir();    
			} 
			path += getFileName();
			return path;
		}
		
		private String getFileName() {
			String fileName = imgUUID + I_Get_Image_Key.JPEG;
			return fileName;
		}
		
		public static Timestamp getNowTimestamp(){
			return new Timestamp(System.currentTimeMillis());
		}
		
		public static String format(Date date, String pattern){
			DateFormat df = new SimpleDateFormat(pattern);
			String s = df.format(date);
			return s;
		}

}
工具類
package com.zufangbao.earth.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * @author Xiepf 2015年12月21日
 */
@Component
public class UploadUtil {

	private static final Log logger = LogFactory.getLog(UploadUtil.class);
	private static final String ACCESS_ID = getValue("ACCESS_ID");
	private static final String ACCESS_KEY = getValue("ACCESS_KEY");
	private static final String BUCKET_NAME = getValue("BUCKET_NAME");
	private static final String END_POINT = getValue("END_POINT");
	private static final String PICTURE_SERVICE = getValue("PICTURE_SERVICE");
	private static final String IMAGE_CONTENT_TYPE = "image/jpeg";

	public static void uploadImage(String filePath) {
		try {
			File file = new File(filePath);
			String key = file.getName();
			String fileType = key.split("\\.")[1];
			OSSClient client = new OSSClient(END_POINT, ACCESS_ID, ACCESS_KEY);
			logger.debug("開始上傳----->");
			uploadImage(client, BUCKET_NAME, key, filePath, fileType);
			logger.debug("上傳完成----->");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void uploadImage(OSSClient client, String bucketName,
			String key, String uploadFilePath, String fileType)
			throws IOException {
		InputStream is = null;
		File file = new File(uploadFilePath);
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());
		objectMeta.setContentType(IMAGE_CONTENT_TYPE);
		try {
			is = new FileInputStream(file);
			client.putObject(bucketName, key, is, objectMeta);
		} finally {
			if (null != is) {
				is.close();
			}
		}
	}

	private static final String HTTP = "http://";
	private static final String POINT = ".";
	private static final String AT = "@";
	private static final String CONNECT = "_";
	private static final String SEPARATOR = "/";
	private static final String TYPE = ".jpg";

	public static String getAliYunUrl() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(HTTP).append(BUCKET_NAME).append(POINT).append(END_POINT)
				.append(SEPARATOR);
		return buffer.toString();
	}

	private static final HashMap<String, String> picuture_service_argument_mapping = new HashMap<String, String>() {
		{
			put("width", "w");
			put("hight", "h");
			put("quality", "q");
			put("Quality", "Q");
			put("multiple", "x");
			put("immobilize", "i");
			put("cut", "c");
			put("edge", "e");
			put("Orient", "o");
		}
	};

	private static final String[] keys = {"width","hight","quality","Quality","multiple","immobilize","cut","edge","Orient"};
 	private static final List<String> keyList = Arrays.asList(keys);
 	/**
 	 * 獲得說略圖URL,根據傳入的Parameters引數
 	 */
 	public String getThumbnail(String fileName,
			HashMap<String, Integer> parameters) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(HTTP).append(BUCKET_NAME).append(POINT)
				.append(PICTURE_SERVICE).append(SEPARATOR).append(fileName)
				.append(AT);

		StringBuffer paraString = new StringBuffer();
		Set<String> keySet = parameters.keySet();
		for (String key : keyList) 
		if(keySet.contains(key)){
			String arugmentString = picuture_service_argument_mapping.get(key);
			if (StringUtils.isEmpty(arugmentString))
				continue;
			paraString.append(CONNECT).append(
					parameters.get(key).toString()
							+ picuture_service_argument_mapping.get(key));
		}
		buffer.append(paraString.toString().substring(1, paraString.length()));

		buffer.append(TYPE);
		return buffer.toString();
	}

	private static final String OSS_PROPERTIES = "oss.properties";

	public static String getValue(String key) {
		Resource imgResource = new ClassPathResource(OSS_PROPERTIES);
		try {
			Properties properties = PropertiesLoaderUtils
					.loadProperties(imgResource);
			return properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

}