Project uses a kindeditor3.4

UploadContentImgAction

  1. @SuppressWarnings("serial")
  2. @ParentPackage("control-center")
  3. public class UploadContentImgAction extends BaseAction {
  4. private File up;
  5. private String upFileName;
  6. private String upContentType;
  7. private String fileDir = "uploads/articleContentImg";
  8. private String imgTitle;
  9. private String align;
  10. private int imgWidth;
  11. private int imgHeight;
  12.  
  13. /**
  14. * kindeditor Picture upload
  15. * @return
  16. * @throws Exception
  17. */
  18. @Action("kindeditorImgUpload")
  19. public String kindeditorImgUpload() throws Exception {
  20. // You can only upload pictures
  21. try {
  22. if(!validatePostfix(upFileName)) {
  23. return "error";
  24. }
  25. User user = (User)getSession().get("user");
  26. String fileRealDir = getServletContext().getRealPath(fileDir);
  27. File file = up;
  28. String fileRealName = createfilename(user.getUserId());
  29. String fileName = fileRealName + upFileName.substring(upFileName.lastIndexOf(".")).toLowerCase();
  30. File newFile = new File(fileRealDir, fileName);
  31. FileUtils.copyFile(file, newFile);
  32. // Compress pictures
  33. ImageUtil.resize(newFile.getPath(), newFile.getPath(), 500);
  34. String id = "contentId";
  35. String url = "/" + fileDir + "/" + fileName;
  36. String border = "0";
  37.  
  38. String result = "<script type='text/javascript'>parent.KE.plugin['image'].insert('" + id + "','" + url + "','" + imgTitle + "','" + imgHeight + "','" + imgHeight + "','" + border + "','" + align + "');</script>";
  39.  
  40. getHttpServletResponse().getWriter().write(result);
  41. } catch (RuntimeException e) {
  42. // TODO Auto-generated catch block
  43. e.printStackTrace();
  44. }
  45. return null;
  46. }
  47. /**
  48. * The file name generation : The current time + Random number + User ID
  49. */
  50. private String createfilename(int userId) {
  51. StringBuilder result = new StringBuilder();
  52. // Get the local time of the current
  53. String now = DateUtil.getLongStrFromDate(new Date());
  54. // In 1000W of randomly generated numbers
  55. int rand = new Random().nextInt(9999999);
  56. // Get rid of - Get rid of : Get rid of the whitespace , Returns the
  57. result.append(now.replace("-", "").replace(":", "").replace(" ", "")).append("_").append(rand).append("_").append(userId);
  58. return result.toString();
  59. }
  60. /**
  61. * Verify that the suffix name should obtain from the configuration file
  62. */
  63. public boolean validatePostfix(String filename) {
  64. // Defines the type of the uploaded file
  65. List<String> fileTypes = new ArrayList<String>();
  66.  
  67. // Picture
  68. fileTypes.add("jpg");
  69. fileTypes.add("jpeg");
  70. fileTypes.add("bmp");
  71. fileTypes.add("gif");
  72. fileTypes.add("png");
  73.  
  74. // Get file mantissa and lowercase
  75. String postfix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
  76. return fileTypes.contains(postfix) ? true : false;
  77. }
  78. public File getUp() {
  79. return up;
  80. }
  81.  
  82. public void setUp(File up) {
  83. this.up = up;
  84. }
  85.  
  86. public String getUpFileName() {
  87. return upFileName;
  88. }
  89.  
  90. public void setUpFileName(String upFileName) {
  91. this.upFileName = upFileName;
  92. }
  93.  
  94. public String getUpContentType() {
  95. return upContentType;
  96. }
  97.  
  98. public void setUpContentType(String upContentType) {
  99. this.upContentType = upContentType;
  100. }
  101.  
  102. public String getImgTitle() {
  103. return imgTitle;
  104. }
  105.  
  106. public void setImgTitle(String imgTitle) {
  107. this.imgTitle = imgTitle;
  108. }
  109.  
  110. public int getImgWidth() {
  111. return imgWidth;
  112. }
  113.  
  114. public void setImgWidth(int imgWidth) {
  115. this.imgWidth = imgWidth;
  116. }
  117.  
  118. public int getImgHeight() {
  119. return imgHeight;
  120. }
  121.  
  122. public void setImgHeight(int imgHeight) {
  123. this.imgHeight = imgHeight;
  124. }
  125.  
  126. public String getAlign() {
  127. return align;
  128. }
  129.  
  130. public void setAlign(String align) {
  131. this.align = align;
  132. }
  133. }

ImageUitl

  1. package com.yancheng.myframe.util;
  2.  
  3. import java.awt.AlphaComposite;
  4. import java.awt.Color;
  5. import java.awt.Font;
  6. import java.awt.Graphics2D;
  7. import java.awt.Image;
  8. import java.awt.geom.AffineTransform;
  9. import java.awt.image.AffineTransformOp;
  10. import java.awt.image.BufferedImage;
  11. import java.io.File;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import javax.imageio.ImageIO;
  15. import magick.ImageInfo;
  16. import magick.MagickImage;
  17. import com.sun.image.codec.jpeg.JPEGCodec;
  18. import com.sun.image.codec.jpeg.JPEGImageEncoder;
  19.  
  20. /**
  21. * @author
  22. *
  23. */
  24. public class ImageUtil {
  25.  
  26. public final static int PHOTO_RATIO = 800; // Scaling the picture coefficient
  27. static{
  28. System.setProperty("jmagick.systemclassloader", "no");
  29. }
  30. /**
  31. * Picture watermark
  32. *
  33. * @param pressImg Watermark picture
  34. * @param targetImg Target picture
  35. * @param x Fixed value defaults in the Middle
  36. * @param y Fixed value defaults in the Middle
  37. * @param alpha Transparency
  38. */
  39. public final static void pressImage(String pressImg, String targetImg,
  40. int x, int y, float alpha) {
  41. try {
  42. File img = new File(targetImg);
  43. Image src = ImageIO.read(img);
  44. int wideth = src.getWidth(null);
  45. int height = src.getHeight(null);
  46. BufferedImage image = new BufferedImage(wideth, height,
  47. BufferedImage.TYPE_INT_RGB);
  48. Graphics2D g = image.createGraphics();
  49. g.drawImage(src, 0, 0, wideth, height, null);
  50. // The watermark file
  51. Image src_biao = ImageIO.read(new File(pressImg));
  52. int wideth_biao = src_biao.getWidth(null);
  53. int height_biao = src_biao.getHeight(null);
  54. g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
  55. alpha));
  56. g.drawImage(src_biao, (wideth - wideth_biao) / 2,
  57. (height - height_biao) / 2, wideth_biao, height_biao, null);
  58. // At the end of the watermark file
  59. g.dispose();
  60. ImageIO.write((BufferedImage) image, "jpg", img);
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. }
  64. }
  65.  
  66. /**
  67. * Text watermark
  68. *
  69. * @param pressText Watermark text
  70. * @param targetImg Target picture
  71. * @param fontName Font name
  72. * @param fontStyle Font style
  73. * @param color Font color
  74. * @param fontSize Font size
  75. * @param x Correction value
  76. * @param y Correction value
  77. * @param alpha Transparency
  78. */
  79. public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x,
  80. int y, float alpha) {
  81. try {
  82. File img = new File(targetImg);
  83. Image src = ImageIO.read(img);
  84. int width = src.getWidth(null);
  85. int height = src.getHeight(null);
  86. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  87. Graphics2D g = image.createGraphics();
  88. g.drawImage(src, 0, 0, width, height, null);
  89. g.setColor(color);
  90. g.setFont(new Font(fontName, fontStyle, fontSize));
  91. g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
  92. g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y);
  93. g.dispose();
  94. ImageIO.write((BufferedImage) image, "jpg", img);
  95. } catch (Exception e) {
  96. e.printStackTrace();
  97. }
  98. }
  99.  
  100. /**
  101. * Zoom effects poor ps : Graphics The following are the AffineTransform under
  102. * Zoom is for " Graphics " Instead of " Image " So after the picture is not clear
  103. * @param filePath The path to the picture
  104. * @param height Height
  105. * @param width Width
  106. * @param bb The ratio is not environmentally friendly farming is required when the
  107. */
  108. public static void resizeImgcale(String filePath, int height, int width, boolean bb) {
  109. try {
  110. double ratio = 0.0; // Scaling
  111. File f = new File(filePath);
  112. BufferedImage bi = ImageIO.read(f);
  113. Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
  114. // Calculate the ratio
  115. if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
  116. if (bi.getHeight() > bi.getWidth()) {
  117. ratio = (new Integer(height)).doubleValue() / bi.getHeight();
  118. } else {
  119. ratio = (new Integer(width)).doubleValue() / bi.getWidth();
  120. }
  121. AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
  122. itemp = op.filter(bi, null);
  123. }
  124. if (bb) {
  125. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  126. Graphics2D g = image.createGraphics();
  127. g.setColor(Color.white);
  128. g.fillRect(0, 0, width, height);
  129. if (width == itemp.getWidth(null))
  130. g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
  131. itemp.getWidth(null), itemp.getHeight(null),
  132. Color.white, null);
  133. else
  134. g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
  135. itemp.getWidth(null), itemp.getHeight(null),
  136. Color.white, null);
  137. g.dispose();
  138. itemp = image;
  139. }
  140. ImageIO.write((BufferedImage) itemp, "jpg", f);
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145.  
  146. /**
  147. * Calculates the length of the word
  148. *
  149. * @param text
  150. * @return
  151. */
  152. public static int getLength(String text) {
  153. int length = 0;
  154. for (int i = 0; i < text.length(); i++) {
  155. if (new String(text.charAt(i) + "").getBytes().length > 1) {
  156. length += 2;
  157. } else {
  158. length += 1;
  159. }
  160. }
  161. return length / 2;
  162. }
  163.  
  164. /**
  165. * Compress pictures
  166. *
  167. * @param imgsrc Source file
  168. * @param imgdist The target file
  169. * @param widthdist Width
  170. * @param heightdist High
  171. */
  172. public static void resizeImg(String imgsrc, String imgdist, int widthdist, int heightdist) {
  173. try {
  174. File srcfile = new File(imgsrc);
  175. if (!srcfile.exists()) {
  176. return;
  177. }
  178. Image src = javax.imageio.ImageIO.read(srcfile);
  179. BufferedImage tag = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
  180. /*
  181. * SCALE_SMOOTH Smooth SCALE: dimensions _AREA_AVERAGING : Scale area average SCALE _FAST : Scale fast
  182. * SCALE_REPLICATE :-Scale replication
  183. */
  184. tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
  185. FileOutputStream out = new FileOutputStream(imgdist);
  186. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  187. encoder.encode(tag);
  188. out.close();
  189. } catch (IOException ex) {
  190. ex.printStackTrace();
  191. }
  192. }
  193.  
  194. /**
  195. * Picture compression
  196. * @param picFrom
  197. * @param picTo
  198. * @param widthdist
  199. * @param heightdist
  200. */
  201. public static void resize(String picFrom, String picTo, int widthdist, int heightdist) {
  202. try {
  203. ImageInfo info = new ImageInfo(picFrom);
  204. MagickImage image = new MagickImage(new ImageInfo(picFrom));
  205. MagickImage scaled = image.scaleImage(widthdist, heightdist);// The small size of the picture file .
  206. scaled.setFileName(picTo);
  207. scaled.writeImage(info);
  208. } catch (Exception ex) {
  209. ex.printStackTrace();
  210. }
  211. }
  212.  
  213. public static void resize(String picFrom, String picTo, int ratio) throws Exception {
  214. BufferedImage bi = ImageIO.read(new File(picFrom));
  215. // The original picture properties
  216. int srcWidth = bi.getWidth();
  217. int srcHeight = bi.getHeight();
  218. // Generate picture properties
  219. int newWidth = srcWidth;
  220. int newHeight = srcHeight;
  221. // If you exceed the maximum width or height is compressed
  222. if (srcWidth > ratio || newHeight > ratio) {
  223. // Generate picture width , height Calculation
  224. if (srcWidth >= srcHeight) {
  225. if (srcWidth < ratio) {
  226. return;
  227. }
  228. newWidth = ratio;
  229. newHeight = (int)(ratio * srcHeight / srcWidth);
  230. } else {
  231. if (srcHeight < ratio) {
  232. return;
  233. }
  234. newHeight = ratio;
  235. newWidth = (int)(ratio * srcWidth / srcHeight);
  236. }
  237. }
  238. resize(picFrom, picTo, newWidth, newHeight);
  239. }
  240.  
  241. public static void resize(String picFrom, String picTo) throws Exception {
  242. resize(picFrom, picTo, PHOTO_RATIO);
  243. }
  244.  
  245. public static void main(String[] args) throws Exception {
  246. // resizeImg("d:/411766.jpg", "d:/411766_1.jpg", 800, 600);
  247. // resize("d:/test_4.jpg", "d:/test_4_2.jpg", 800);
  248. pressText(" Joy and the damned ", "d:/411766.jpg", " Simplified Chinese ", Font.ITALIC, Color.black, 90, 40, 80, 0.5f);
  249. }
  250.  
  251. }

struts2 using kindeditor upload pictures (including jmagic compressed images)的更多相关文章

  1. kindeditor在光标处插入编辑器外的数据

    页面 <div class="form-group clearfix"> <label class="control-label col-sm-3 co ...

  2. kindeditor的简单使用

    上传到云: 一.引入kindeditor <%@ page language="java" contentType="text/html; charset=UTF- ...

  3. KindEditor图片批量上传

    KindEditor编辑器图片批量上传采用了上传插件swfupload.swf,所以后台上传文件方法返回格式应为JSONObject的String格式(注). JSONObject格式: JSONOb ...

  4. Kindeditor放置两个调用readonly错误

    开始 需要调用Kindeditor中的readonly的方法,但是一直提示edit is undefined 而editor.readonly(true)又只对第一个对象有效 所以只能换换形式,干脆将 ...

  5. kindeditor在Java项目中的应用以及图片上传配置

    在官网下载Kindededitor的开发包   在项目中javaweb项目中导入kindeditor必须要使用的Jar包(用于文件上传,除非你的富文本编辑器不使用图片上传)jar包可以在官网的开发包中 ...

  6. Gulp.js简介

    Gulp.js简介 我们讨论了很多关于怎么减少页面体积,提高重网站性能的方法.有些是操作是一劳永逸的,如开启服务器的gzip压缩,使用适当的图片格式,或删除一些不必要的字符.但有一些任务是每次工作都必 ...

  7. [翻译]Gulp.js简介

    我们讨论了很多关于怎么减少页面体积,提高重网站性能的方法.有些是操作是一劳永逸的,如开启服务器的gzip压缩,使用适当的图片格式,或删除一些不必要的字符.但有一些任务是每次工作都必须反复执行的.如 新 ...

  8. playframework中多附件上传注意事项

    playframework中多附件上传注意事项 2013年09月24日 play 暂无评论 //play版本问题 经确认,1.0.3.2版本下控制器中方法参数  List<File> fi ...

  9. 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 ...

随机推荐

  1. CentOS下搭建NFS服务器总结

    环境介绍: . 服务器: 192.168.0.100 . 客户机: 192.168.0.101 安装软件包: . 服务器和客户机都要安装nfs 和 rpcbind 软件包: yum -y instal ...

  2. 菜鸟学习WCF笔记-概念

    背景 WCF这个词语一直不陌生,以前也使用过多次在实际的项目中,但是一直没有时间来做个系统的学习,最近抽点时间,看看 蒋金楠的<WCF全面解析>学习下,顺带做些笔记,如有错误,欢迎各路大神 ...

  3. SpringMVC 架构

    SpringMVC 架构 1. 前言 SpringMVC是目前java世界中最为广泛应用的web框架,最然从学习SpringMVC的第一个程序--helloworld至今,已有好几个年头.其间伴随着项 ...

  4. python基于LeanCloud的短信验证

    python基于LeanCloud的短信验证 1. 获取LeanCloud的Id.Key 2. 安装Flask框架和Requests库 pip install flask pip install re ...

  5. Windows Server 2008 R2 备份和恢复 (转)

    Windows Server Backup : 1.安装Windows Server Backup的方法: 通过"服务器管理器"中的"添加功能"向导进行安装. ...

  6. Windows共享内存示例

    共享内存主要是通过映射机制实现的. Windows 下进程的地址空间在逻辑上是相互隔离的,但在物理上却是重叠的.所谓的重叠是指同一块内存区域可能被多个进程同时使用.当调用 CreateFileMapp ...

  7. 让树莓派说出自己的IP地址

    当亲爱的树莓派没有显示器时如何控制它?对,就是ssh,但是ssh需要IP地址啊,树莓派的IP地址是多少?这个问题问的好,目前大约有这样几种解决方案:. 获取到IP地址后将地址发到邮箱:前提是树莓派能上 ...

  8. ip校验方法:判断ip是否位于指定的范围内

    import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util.reg ...

  9. 在Linq to Entity 中使用lambda表达式来实现Left Join和Join

    1.读取用户和部门两个表的左连接: var sg = db.Users.GroupJoin(db.Departments, u => u.DepartmentId, d => d.Depa ...

  10. 持续集成(二)环境搭建篇—内网邮件server搭建

    在我们的持续构建中,项目构建中出现错误提醒.或者开发者之间的沟通交流,进度汇报的事务,都是离不开一个通信工具.那就是邮件.在我们的项目开发中假设使用第三方的邮件平台,这肯定不是最好的选择.由于第三方的 ...