import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
/**
* @author xiaojie
*添加水印工具类
*/
public class PictureWaterMarkUtil {
/**
* @param srcImgPath 源图片路径
* @param tarImgPath 保存的图片路径
* @param waterMarkContent 水印内容
* @param markContentColor 水印颜色
* @param font 水印字体
*/
public static void addWaterMark(String srcImgPath, String tarImgPath) {
try {
// 读取原图片信息
File srcImgFile = new File(srcImgPath);//得到文件
Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
int srcImgHeight = srcImg.getHeight(null);//获取图片的高
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
Color color=new Color(255,255,255,80); //水印图片色彩以及透明度
g.setColor(color); //根据图片的背景设置水印颜色
Font font = new Font("微软雅黑", Font.ITALIC,80);
g.setFont(font);//设置字体
//设置倾斜
g.rotate(Math.toRadians(-30), bufImg.getWidth() / 2,
bufImg.getHeight() / 2);
//设置水印的坐标
//右下角
// int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3;
// int y = srcImgHeight - 3;
//中间
String waterMarkContent="测试水印"; //水印内容
int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g)) / 2;
int y = srcImgHeight / 2;
g.drawString(waterMarkContent, x, y); //画出水印
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
ImageIO.write(bufImg, "jpg", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
public static void main(String[] args) {
String srcImgPath="D:/Personal/Desktop/商品素材/3.jpg"; //源图片地址
String tarImgPath="D:/test/1.jpg"; //待存储的地址
addWaterMark(srcImgPath, tarImgPath);
System.out.println("添加成功");
}
}
public class FtpUtil {
/**
* Description: 向FTP服务器上传文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2017/11/01。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
//切换到上传目录
if (!ftp.changeWorkingDirectory(basePath+filePath)) {
//如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上传文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* Description: 从FTP服务器下载文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
String fileName, String localPath) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
public class PicServiceImpl implements PicService {
@Value("${FTP_USERNAME}")
private String FTP_USERNAME;
@Value("${FTP_PASSWORD}")
private String FTP_PASSWORD;
@Value("${FTP_PORT}")
private Integer FTP_PORT;
@Value("${FTP_ADDRESS}")
private String FTP_ADDRESS;
@Value("${FTP_BASE_PATH}")
private String FTP_BASE_PATH;
@Value("${IMAGE_BASE_PATH}")
private String IMAGE_BASE_PATH;
@MethodLog(moduleName="图片管理模块",option = "上传图片")
@Override
public Map<String,Object> uploadPicture(MultipartFile uploadFile) {
//获取源图片地址
File f = null;
File outfile=null;
String orginalPath=null;
String tarpath=null;
try {
f=File.createTempFile("tmp", null);//创建临时文件
uploadFile.transferTo(f);//转换MultipartFile
outfile=File.createTempFile("outtmp", null);//创建临时存放输出水印图片的文件
orginalPath=f.getAbsolutePath();//获取源文件路径
tarpath=outfile.getAbsolutePath();//设定临时写出的文件路径
PictureWaterMarkUtil.addWaterMark(orginalPath, tarpath);//添加水印
InputStream is = new FileInputStream(tarpath);//将临时文件转换成输出流
// 生成新的文件名
// 取文件原始名字
String oldName = uploadFile.getOriginalFilename();
// 生成新的文件名
String newName = IDUtils.genImageName();
newName = newName + oldName.substring(oldName.lastIndexOf("."));
String imagePath = new DateTime().toString("/yyyy/MM/dd");
String url = IMAGE_BASE_PATH + imagePath + "/" + newName;
Map<String,Object> resultMap = new HashMap<String,Object>();
boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH,
imagePath, newName, is);
if (!result) {
resultMap.put("error", 1);
resultMap.put("message", "文件上传失败");
return resultMap;
}
resultMap.put("error", 0);
resultMap.put("url", url);
outfile.deleteOnExit(); //删除临时创建文件
f.deleteOnExit(); //删除临时创建文件
return resultMap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
@Controller
public class PicController {
@Autowired
private PicService picService;
@RequestMapping("/pic/upload")
@ResponseBody
public String pictureUpload(MultipartFile uploadFile){
Map result=picService.uploadPicture(uploadFile);
String jsonResult=JsonUtils.objectToJson(result);
return jsonResult;
}
}