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);
}
}