struts2 using kindeditor upload pictures (including jmagic compressed images)
Project uses a kindeditor3.4
UploadContentImgAction
- @SuppressWarnings("serial")
- @ParentPackage("control-center")
- public class UploadContentImgAction extends BaseAction {
- private File up;
- private String upFileName;
- private String upContentType;
- private String fileDir = "uploads/articleContentImg";
- private String imgTitle;
- private String align;
- private int imgWidth;
- private int imgHeight;
- /**
- * kindeditor Picture upload
- * @return
- * @throws Exception
- */
- @Action("kindeditorImgUpload")
- public String kindeditorImgUpload() throws Exception {
- // You can only upload pictures
- try {
- if(!validatePostfix(upFileName)) {
- return "error";
- }
- User user = (User)getSession().get("user");
- String fileRealDir = getServletContext().getRealPath(fileDir);
- File file = up;
- String fileRealName = createfilename(user.getUserId());
- String fileName = fileRealName + upFileName.substring(upFileName.lastIndexOf(".")).toLowerCase();
- File newFile = new File(fileRealDir, fileName);
- FileUtils.copyFile(file, newFile);
- // Compress pictures
- ImageUtil.resize(newFile.getPath(), newFile.getPath(), 500);
- String id = "contentId";
- String url = "/" + fileDir + "/" + fileName;
- String border = "0";
- String result = "<script type='text/javascript'>parent.KE.plugin['image'].insert('" + id + "','" + url + "','" + imgTitle + "','" + imgHeight + "','" + imgHeight + "','" + border + "','" + align + "');</script>";
- getHttpServletResponse().getWriter().write(result);
- } catch (RuntimeException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- /**
- * The file name generation : The current time + Random number + User ID
- */
- private String createfilename(int userId) {
- StringBuilder result = new StringBuilder();
- // Get the local time of the current
- String now = DateUtil.getLongStrFromDate(new Date());
- // In 1000W of randomly generated numbers
- int rand = new Random().nextInt(9999999);
- // Get rid of - Get rid of : Get rid of the whitespace , Returns the
- result.append(now.replace("-", "").replace(":", "").replace(" ", "")).append("_").append(rand).append("_").append(userId);
- return result.toString();
- }
- /**
- * Verify that the suffix name should obtain from the configuration file
- */
- public boolean validatePostfix(String filename) {
- // Defines the type of the uploaded file
- List<String> fileTypes = new ArrayList<String>();
- // Picture
- fileTypes.add("jpg");
- fileTypes.add("jpeg");
- fileTypes.add("bmp");
- fileTypes.add("gif");
- fileTypes.add("png");
- // Get file mantissa and lowercase
- String postfix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
- return fileTypes.contains(postfix) ? true : false;
- }
- public File getUp() {
- return up;
- }
- public void setUp(File up) {
- this.up = up;
- }
- public String getUpFileName() {
- return upFileName;
- }
- public void setUpFileName(String upFileName) {
- this.upFileName = upFileName;
- }
- public String getUpContentType() {
- return upContentType;
- }
- public void setUpContentType(String upContentType) {
- this.upContentType = upContentType;
- }
- public String getImgTitle() {
- return imgTitle;
- }
- public void setImgTitle(String imgTitle) {
- this.imgTitle = imgTitle;
- }
- public int getImgWidth() {
- return imgWidth;
- }
- public void setImgWidth(int imgWidth) {
- this.imgWidth = imgWidth;
- }
- public int getImgHeight() {
- return imgHeight;
- }
- public void setImgHeight(int imgHeight) {
- this.imgHeight = imgHeight;
- }
- public String getAlign() {
- return align;
- }
- public void setAlign(String align) {
- this.align = align;
- }
- }
ImageUitl
- package com.yancheng.myframe.util;
- import java.awt.AlphaComposite;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics2D;
- import java.awt.Image;
- import java.awt.geom.AffineTransform;
- import java.awt.image.AffineTransformOp;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- import magick.ImageInfo;
- import magick.MagickImage;
- import com.sun.image.codec.jpeg.JPEGCodec;
- import com.sun.image.codec.jpeg.JPEGImageEncoder;
- /**
- * @author
- *
- */
- public class ImageUtil {
- public final static int PHOTO_RATIO = 800; // Scaling the picture coefficient
- static{
- System.setProperty("jmagick.systemclassloader", "no");
- }
- /**
- * Picture watermark
- *
- * @param pressImg Watermark picture
- * @param targetImg Target picture
- * @param x Fixed value defaults in the Middle
- * @param y Fixed value defaults in the Middle
- * @param alpha Transparency
- */
- public final static void pressImage(String pressImg, String targetImg,
- int x, int y, float alpha) {
- try {
- File img = new File(targetImg);
- Image src = ImageIO.read(img);
- int wideth = src.getWidth(null);
- int height = src.getHeight(null);
- BufferedImage image = new BufferedImage(wideth, height,
- BufferedImage.TYPE_INT_RGB);
- Graphics2D g = image.createGraphics();
- g.drawImage(src, 0, 0, wideth, height, null);
- // The watermark file
- Image src_biao = ImageIO.read(new File(pressImg));
- int wideth_biao = src_biao.getWidth(null);
- int height_biao = src_biao.getHeight(null);
- g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
- alpha));
- g.drawImage(src_biao, (wideth - wideth_biao) / 2,
- (height - height_biao) / 2, wideth_biao, height_biao, null);
- // At the end of the watermark file
- g.dispose();
- ImageIO.write((BufferedImage) image, "jpg", img);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * Text watermark
- *
- * @param pressText Watermark text
- * @param targetImg Target picture
- * @param fontName Font name
- * @param fontStyle Font style
- * @param color Font color
- * @param fontSize Font size
- * @param x Correction value
- * @param y Correction value
- * @param alpha Transparency
- */
- public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x,
- int y, float alpha) {
- try {
- File img = new File(targetImg);
- Image src = ImageIO.read(img);
- int width = src.getWidth(null);
- int height = src.getHeight(null);
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- Graphics2D g = image.createGraphics();
- g.drawImage(src, 0, 0, width, height, null);
- g.setColor(color);
- g.setFont(new Font(fontName, fontStyle, fontSize));
- g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
- g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y);
- g.dispose();
- ImageIO.write((BufferedImage) image, "jpg", img);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * Zoom effects poor ps : Graphics The following are the AffineTransform under
- * Zoom is for " Graphics " Instead of " Image " So after the picture is not clear
- * @param filePath The path to the picture
- * @param height Height
- * @param width Width
- * @param bb The ratio is not environmentally friendly farming is required when the
- */
- public static void resizeImgcale(String filePath, int height, int width, boolean bb) {
- try {
- double ratio = 0.0; // Scaling
- File f = new File(filePath);
- BufferedImage bi = ImageIO.read(f);
- Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
- // Calculate the ratio
- if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
- if (bi.getHeight() > bi.getWidth()) {
- ratio = (new Integer(height)).doubleValue() / bi.getHeight();
- } else {
- ratio = (new Integer(width)).doubleValue() / bi.getWidth();
- }
- AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
- itemp = op.filter(bi, null);
- }
- if (bb) {
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- Graphics2D g = image.createGraphics();
- g.setColor(Color.white);
- g.fillRect(0, 0, width, height);
- if (width == itemp.getWidth(null))
- g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
- itemp.getWidth(null), itemp.getHeight(null),
- Color.white, null);
- else
- g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
- itemp.getWidth(null), itemp.getHeight(null),
- Color.white, null);
- g.dispose();
- itemp = image;
- }
- ImageIO.write((BufferedImage) itemp, "jpg", f);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Calculates the length of the word
- *
- * @param text
- * @return
- */
- public static int getLength(String text) {
- int length = 0;
- for (int i = 0; i < text.length(); i++) {
- if (new String(text.charAt(i) + "").getBytes().length > 1) {
- length += 2;
- } else {
- length += 1;
- }
- }
- return length / 2;
- }
- /**
- * Compress pictures
- *
- * @param imgsrc Source file
- * @param imgdist The target file
- * @param widthdist Width
- * @param heightdist High
- */
- public static void resizeImg(String imgsrc, String imgdist, int widthdist, int heightdist) {
- try {
- File srcfile = new File(imgsrc);
- if (!srcfile.exists()) {
- return;
- }
- Image src = javax.imageio.ImageIO.read(srcfile);
- BufferedImage tag = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
- /*
- * SCALE_SMOOTH Smooth SCALE: dimensions _AREA_AVERAGING : Scale area average SCALE _FAST : Scale fast
- * SCALE_REPLICATE :-Scale replication
- */
- tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
- FileOutputStream out = new FileOutputStream(imgdist);
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
- encoder.encode(tag);
- out.close();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- /**
- * Picture compression
- * @param picFrom
- * @param picTo
- * @param widthdist
- * @param heightdist
- */
- public static void resize(String picFrom, String picTo, int widthdist, int heightdist) {
- try {
- ImageInfo info = new ImageInfo(picFrom);
- MagickImage image = new MagickImage(new ImageInfo(picFrom));
- MagickImage scaled = image.scaleImage(widthdist, heightdist);// The small size of the picture file .
- scaled.setFileName(picTo);
- scaled.writeImage(info);
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public static void resize(String picFrom, String picTo, int ratio) throws Exception {
- BufferedImage bi = ImageIO.read(new File(picFrom));
- // The original picture properties
- int srcWidth = bi.getWidth();
- int srcHeight = bi.getHeight();
- // Generate picture properties
- int newWidth = srcWidth;
- int newHeight = srcHeight;
- // If you exceed the maximum width or height is compressed
- if (srcWidth > ratio || newHeight > ratio) {
- // Generate picture width , height Calculation
- if (srcWidth >= srcHeight) {
- if (srcWidth < ratio) {
- return;
- }
- newWidth = ratio;
- newHeight = (int)(ratio * srcHeight / srcWidth);
- } else {
- if (srcHeight < ratio) {
- return;
- }
- newHeight = ratio;
- newWidth = (int)(ratio * srcWidth / srcHeight);
- }
- }
- resize(picFrom, picTo, newWidth, newHeight);
- }
- public static void resize(String picFrom, String picTo) throws Exception {
- resize(picFrom, picTo, PHOTO_RATIO);
- }
- public static void main(String[] args) throws Exception {
- // resizeImg("d:/411766.jpg", "d:/411766_1.jpg", 800, 600);
- // resize("d:/test_4.jpg", "d:/test_4_2.jpg", 800);
- pressText(" Joy and the damned ", "d:/411766.jpg", " Simplified Chinese ", Font.ITALIC, Color.black, 90, 40, 80, 0.5f);
- }
- }
struts2 using kindeditor upload pictures (including jmagic compressed images)的更多相关文章
- kindeditor在光标处插入编辑器外的数据
页面 <div class="form-group clearfix"> <label class="control-label col-sm-3 co ...
- kindeditor的简单使用
上传到云: 一.引入kindeditor <%@ page language="java" contentType="text/html; charset=UTF- ...
- KindEditor图片批量上传
KindEditor编辑器图片批量上传采用了上传插件swfupload.swf,所以后台上传文件方法返回格式应为JSONObject的String格式(注). JSONObject格式: JSONOb ...
- Kindeditor放置两个调用readonly错误
开始 需要调用Kindeditor中的readonly的方法,但是一直提示edit is undefined 而editor.readonly(true)又只对第一个对象有效 所以只能换换形式,干脆将 ...
- kindeditor在Java项目中的应用以及图片上传配置
在官网下载Kindededitor的开发包 在项目中javaweb项目中导入kindeditor必须要使用的Jar包(用于文件上传,除非你的富文本编辑器不使用图片上传)jar包可以在官网的开发包中 ...
- Gulp.js简介
Gulp.js简介 我们讨论了很多关于怎么减少页面体积,提高重网站性能的方法.有些是操作是一劳永逸的,如开启服务器的gzip压缩,使用适当的图片格式,或删除一些不必要的字符.但有一些任务是每次工作都必 ...
- [翻译]Gulp.js简介
我们讨论了很多关于怎么减少页面体积,提高重网站性能的方法.有些是操作是一劳永逸的,如开启服务器的gzip压缩,使用适当的图片格式,或删除一些不必要的字符.但有一些任务是每次工作都必须反复执行的.如 新 ...
- playframework中多附件上传注意事项
playframework中多附件上传注意事项 2013年09月24日 play 暂无评论 //play版本问题 经确认,1.0.3.2版本下控制器中方法参数 List<File> fi ...
- Creating a new Signiant Transfer Engine because the previous transfer had to be canceled.
From: http://stackoverflow.com/questions/10548196/application-loader-new-weird-warning-about-signian ...
随机推荐
- CentOS下搭建NFS服务器总结
环境介绍: . 服务器: 192.168.0.100 . 客户机: 192.168.0.101 安装软件包: . 服务器和客户机都要安装nfs 和 rpcbind 软件包: yum -y instal ...
- 菜鸟学习WCF笔记-概念
背景 WCF这个词语一直不陌生,以前也使用过多次在实际的项目中,但是一直没有时间来做个系统的学习,最近抽点时间,看看 蒋金楠的<WCF全面解析>学习下,顺带做些笔记,如有错误,欢迎各路大神 ...
- SpringMVC 架构
SpringMVC 架构 1. 前言 SpringMVC是目前java世界中最为广泛应用的web框架,最然从学习SpringMVC的第一个程序--helloworld至今,已有好几个年头.其间伴随着项 ...
- python基于LeanCloud的短信验证
python基于LeanCloud的短信验证 1. 获取LeanCloud的Id.Key 2. 安装Flask框架和Requests库 pip install flask pip install re ...
- Windows Server 2008 R2 备份和恢复 (转)
Windows Server Backup : 1.安装Windows Server Backup的方法: 通过"服务器管理器"中的"添加功能"向导进行安装. ...
- Windows共享内存示例
共享内存主要是通过映射机制实现的. Windows 下进程的地址空间在逻辑上是相互隔离的,但在物理上却是重叠的.所谓的重叠是指同一块内存区域可能被多个进程同时使用.当调用 CreateFileMapp ...
- 让树莓派说出自己的IP地址
当亲爱的树莓派没有显示器时如何控制它?对,就是ssh,但是ssh需要IP地址啊,树莓派的IP地址是多少?这个问题问的好,目前大约有这样几种解决方案:. 获取到IP地址后将地址发到邮箱:前提是树莓派能上 ...
- ip校验方法:判断ip是否位于指定的范围内
import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util.reg ...
- 在Linq to Entity 中使用lambda表达式来实现Left Join和Join
1.读取用户和部门两个表的左连接: var sg = db.Users.GroupJoin(db.Departments, u => u.DepartmentId, d => d.Depa ...
- 持续集成(二)环境搭建篇—内网邮件server搭建
在我们的持续构建中,项目构建中出现错误提醒.或者开发者之间的沟通交流,进度汇报的事务,都是离不开一个通信工具.那就是邮件.在我们的项目开发中假设使用第三方的邮件平台,这肯定不是最好的选择.由于第三方的 ...