tup

16257 ワード

package com.zjapl.erecord.core.common.img;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.csource.common.MyException;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.zjapl.erecord.application.base.entity.ERecordImag;
import com.zjapl.erecord.core.common.log.BaseLogger;
import com.zjapl.erecord.core.common.utils.FdfsUtils;
import com.zjapl.erecord.core.common.utils.MD5Util;

/**
 * @author wull
 */
public class ImageUtil extends BaseLogger {
	private MultipartFile mf;
	private String transFileName;
	private String zipFileName;
	private String fileExt;
	private static final String FILE_POINT = ".";
	private static final String ZIP_NAME_END = "-zip";
	private static final int IMG_WIDTH_DEFAULT = 500;

	public ImageUtil(String transFileNameX) throws MyException{
		super();
		doPreFdfs(transFileNameX);
	}
	
	public ImageUtil(MultipartFile mf) {
		super();
		this.mf = mf;
		work();
	}
	
	/**
	 *        ,    【    】
	 * 
	 * @param mf
	 * @return
	 */
	private void work() {
		String fileName = mf.getOriginalFilename();
		//         
		calFileExt(fileName);

		String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//      ,  String   
		// String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");//       UUID。
		//        
		String rand = String.valueOf(Math.random() * 9000 + 1000).substring(0, 4);
		// String newFileName = dateStr + "-" + rand + (suffix != null ? suffix : "");//       。

		String tempName = dateStr + "-" + rand;//       。
		this.transFileName = tempName + FILE_POINT + this.fileExt;//       。
		this.zipFileName = tempName + ZIP_NAME_END + FILE_POINT + this.fileExt;//       。

	}

	/**
	 *         
	 * 
	 * @param fileName
	 */
	private void calFileExt(String fileName) {
		//         
		this.fileExt = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length()) : null;
	}

	private String calFileNameWithOutExt(String fileName) {
		return fileName.indexOf(".") != -1 ? fileName.substring(0, fileName.lastIndexOf(".")) : null;
	}

	/**
	 *     
	 * 
	 * @return
	 * @throws IOException
	 */
	public File upload() throws IOException {
		File transFile = new File(System.getProperty("java.io.tmpdir") + this.transFileName);
		FileCopyUtils.copy(this.mf.getBytes(), transFile);
		return transFile;
	}

	/**
	 *        
	 * 
	 * @return
	 * @throws IOException
	 */
	private File zipWarter() throws IOException {
		String uploadTmpDir = System.getProperty("java.io.tmpdir");
		File zipFile = new File(uploadTmpDir + this.zipFileName);
		ImageZip.zip(new File(uploadTmpDir + this.transFileName), zipFile, IMG_WIDTH_DEFAULT, this.fileExt);

		ImageWarter.warter("        ", uploadTmpDir + this.zipFileName);

		return new File(uploadTmpDir + this.zipFileName);
	}

	private void doPreFdfs(String transFileNameX) throws MyException {
		if(new File(System.getProperty("java.io.tmpdir")+transFileNameX).exists() == false){
			throw new MyException("    ["+transFileNameX+"]   !");
		}
		
		this.transFileName = transFileNameX;
		calFileExt(this.transFileName);

		this.zipFileName = calFileNameWithOutExt(this.transFileName) + ZIP_NAME_END + FILE_POINT + this.fileExt;

	}
	
	public ERecordImag trans2Fdfs(String tableName, String recordId)
			throws IOException, MyException {
		File transFile = new File(System.getProperty("java.io.tmpdir") + this.transFileName);
		FdfsUtils fdfs = new FdfsUtils();

		ERecordImag imagInfo = new ERecordImag();
		//   ID:
		imagInfo.setRecordId(recordId);
		//   MD5
		imagInfo.setMd5(MD5Util.getMD5(transFile));
		//     
		imagInfo.setFileSize(String.valueOf(transFile.length()));
		//     
		imagInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));

		//           
		File zipFile = zipWarter();
		imagInfo.setZipFileSize(String.valueOf(zipFile.length()));
		imagInfo.setZipMd5(MD5Util.getMD5(zipFile));

		try {
			{
				String[] groupNames = fdfs.upload(transFile.getPath());
				int fisrtFlag = groupNames[0].indexOf("/");
				//     
				imagInfo.setGroupName(groupNames[0].substring(0, fisrtFlag));
				//       
				imagInfo.setFilePath(groupNames[0].substring(fisrtFlag));
				log.debug("------------->" + transFile.getName() + " saveToFdfs succ...");
				//       
				transFile.delete();
			}

			{
				String[] zipGroupNames = fdfs.upload(zipFile.getPath());
				int fisrtFlag2 = zipGroupNames[0].indexOf("/");
				//       
				imagInfo.setZipGroupName(zipGroupNames[0].substring(0, fisrtFlag2));
				//         
				imagInfo.setZipFilePath(zipGroupNames[0].substring(fisrtFlag2));
				log.debug("------------->ZIP_FILE " + zipFile.getName() + " saveToFdfs succ...");

				//       
				zipFile.delete();
			}

		} finally {
			try {
				fdfs.close();
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
		return imagInfo;
	}

//	public ERecordImag trans2Fdfs(String transfileNameX, String tableName, String recordId)
//			throws IOException, MyException {
//		//     
//		doPreFdfs(transfileNameX);
//		return this.trans2Fdfs(tableName, recordId);
//	}

	public static void main(String[] args) {
		// String fileName = "aa.jpg";
		// String ext = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1,
		// fileName.length())
		// : null;
		
		File f= new File("D:\\7.jpg");
		System.out.println(f.getName());
	}

}

2
package com.zjapl.erecord.core.common.img;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 *    :warter(String pressText, String targetImg) 
 * @author wull
 *
 */
public class ImageWarter {
	public ImageWarter() {
	}

	/**
	 *          
	 * 
	 * @param pressImg --
	 *                
	 * @param targetImg --
	 *                
	 * @param x
	 *            --X  
	 * @param y
	 *            --y  
	 */
	public final static void warter(String pressImg, String targetImg,	int x, int y) {
		try {
			//     
			File _file = new File(targetImg);
			Image src = ImageIO.read(_file);
			//        
			int wideth = src.getWidth(null);
			//        
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = image.createGraphics();
			g.drawImage(src, 0, 0, wideth, height, null);
			//     
			File _filebiao = new File(pressImg);
			Image src_biao = ImageIO.read(_filebiao);
			//          
			int wideth_biao = src_biao.getWidth(null);
			//          
			int height_biao = src_biao.getHeight(null);
			//            x==-1,y==-1,           
			if (x == -1 && y == -1) {
				g.drawImage(src_biao, wideth - wideth_biao, height - height_biao, wideth_biao, height_biao, null);
			} else {
				g.drawImage(src_biao, x, y, wideth_biao, height_biao, null);
			}
			//       
			g.dispose();
			FileOutputStream out = new FileOutputStream(targetImg);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/***************************************************************************
	 *         
	 * 
	 * @param pressText
	 *            --  
	 * @param targetImg --
	 *                
	 */
	public static void warter(String pressText, String targetImg) {
		warter(pressText, targetImg, "    ", 0, Color.LIGHT_GRAY, 20,
				40, 40);
	}

	/***************************************************************************
	 *         
	 * 
	 * @param pressText
	 *            --  
	 * @param targetImg --
	 *                
	 * @param fontName --
	 *               
	 * @param fontStyle --
	 *                
	 * @param color --
	 *                     
	 * @param x
	 *            x   
	 * @param y
	 *            y   
	 */
	private static void warter(String pressText, String targetImg, String fontName, int fontStyle, Color color,
			int fontSize, int x, int y) {
		try {
			System.out.println(targetImg);
			File _file = new File(targetImg);
			Image src = ImageIO.read(_file);
			int wideth = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = image.createGraphics();
			g.drawImage(src, 0, 0, wideth, height, null);
			if (color == null) {
				g.setColor(Color.black);
			} else {
				g.setColor(color);
			}
			g.setFont(new Font(fontName, fontStyle, fontSize));
			//             ,                 ,        ,    
			byte[] bytes = pressText.getBytes();
			int i = bytes.length;// i     
			int j = pressText.length();// j     
			//   i==j        
			if (i == j) {
				g.drawString(pressText, (int) (wideth - (fontSize * (pressText.length() / 2.0)) - x), height - y);
			} else {
				g.drawString(pressText, (int) (wideth - (fontSize * pressText.length()) - x), height - y);
			}
			g.dispose();
			FileOutputStream out = new FileOutputStream(targetImg);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image);
			out.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

3/
package com.zjapl.erecord.core.common.img;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


/**
 *       :zip(File originalFile, File resizedFile, int width, String format) throws IOException
 * @author wull
 */
public class ImageZip {
	public static final MediaTracker tracker = new MediaTracker(new Component() {
		private static final long serialVersionUID = 1234162663955668507L;
	});

	/**
	 * @param originalFile    
	 * @param resizedFile       
	 * @param width    
	 * @param format      jpg, png, gif(   )
	 * @throws IOException
	 */
	public static void zip(File originalFile, File resizedFile, int width, String format) throws IOException {
		if (format != null && "gif".equals(format.toLowerCase())) {
			resize(originalFile, resizedFile, width, 1);
			return;
		}
		FileInputStream fis = new FileInputStream(originalFile);
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		int readLength = -1;
		int bufferSize = 1024;
		byte bytes[] = new byte[bufferSize];
		while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
			byteStream.write(bytes, 0, readLength);
		}
		byte[] in = byteStream.toByteArray();
		fis.close();
		byteStream.close();

		Image inputImage = Toolkit.getDefaultToolkit().createImage(in);
		waitForImage(inputImage);
		int imageWidth = inputImage.getWidth(null);
		if (imageWidth < 1)
			throw new IllegalArgumentException("image width " + imageWidth + " is out of range");
		int imageHeight = inputImage.getHeight(null);
		if (imageHeight < 1)
			throw new IllegalArgumentException("image height " + imageHeight + " is out of range");

		// Create output image.
		int height = -1;
		double scaleW = (double) imageWidth / (double) width;
		double scaleY = (double) imageHeight / (double) height;
		if (scaleW >= 0 && scaleY >= 0) {
			if (scaleW > scaleY) {
				height = -1;
			} else {
				width = -1;
			}
		}
		Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT);
		checkImage(outputImage);
		encode(new FileOutputStream(resizedFile), outputImage, format);
	}

	/** Checks the given image for valid width and height. */
	private static void checkImage(Image image) {
		waitForImage(image);
		int imageWidth = image.getWidth(null);
		if (imageWidth < 1)
			throw new IllegalArgumentException("image width " + imageWidth + " is out of range");
		int imageHeight = image.getHeight(null);
		if (imageHeight < 1)
			throw new IllegalArgumentException("image height " + imageHeight + " is out of range");
	}

	/** Waits for given image to load. Use before querying image height/width/colors. */
	private static void waitForImage(Image image) {
		try {
			tracker.addImage(image, 0);
			tracker.waitForID(0);
			tracker.removeImage(image, 0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/** Encodes the given image at the given quality to the output stream. */
	private static void encode(OutputStream outputStream, Image outputImage, String format) throws java.io.IOException {
		int outputWidth = outputImage.getWidth(null);
		if (outputWidth < 1)
			throw new IllegalArgumentException("output image width " + outputWidth + " is out of range");
		int outputHeight = outputImage.getHeight(null);
		if (outputHeight < 1)
			throw new IllegalArgumentException("output image height " + outputHeight + " is out of range");

		// Get a buffered image from the image.
		BufferedImage bi = new BufferedImage(outputWidth, outputHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D biContext = bi.createGraphics();
		biContext.drawImage(outputImage, 0, 0, null);
		ImageIO.write(bi, format, outputStream);
		outputStream.flush();
	}

	/**
	 *   gif  
	 * 
	 * @param originalFile    
	 * @param resizedFile       
	 * @param newWidth   
	 * @param quality      (   )
	 * @throws IOException
	 */
	private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
		if (quality < 0 || quality > 1) {
			throw new IllegalArgumentException("Quality has to be between 0 and 1");
		}
		ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
		Image i = ii.getImage();
		Image resizedImage = null;
		int iWidth = i.getWidth(null);
		int iHeight = i.getHeight(null);
		if (iWidth > iHeight) {
			resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
		} else {
			resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
		}
		// This code ensures that all the pixels in the image are loaded.
		Image temp = new ImageIcon(resizedImage).getImage();
		// Create the buffered image.
		BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
				BufferedImage.TYPE_INT_RGB);
		// Copy image to buffered image.
		Graphics g = bufferedImage.createGraphics();
		// Clear background and paint the image.
		g.setColor(Color.white);
		g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
		g.drawImage(temp, 0, 0, null);
		g.dispose();
		// Soften.
		float softenFactor = 0.05f;
		float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0,
				softenFactor, 0 };
		Kernel kernel = new Kernel(3, 3, softenArray);
		ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
		bufferedImage = cOp.filter(bufferedImage, null);
		// Write the jpeg to a file.
		FileOutputStream out = new FileOutputStream(resizedFile);
		// Encodes image as a JPEG data stream
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
		param.setQuality(quality, true);
		encoder.setJPEGEncodeParam(param);
		encoder.encode(bufferedImage);
	}
}