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)的更多相关文章

  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. 【Android】AppCompat V21:将 Materia Design 兼容到5.0之前的设备

    AppCompat V21:将 Materia Design 兼容到于5.0之前的设备 本篇文章翻译自Chris Banes(就职于Google,是Android-PullToRefresh,Phot ...

  2. BOM (Browser Object Model) 浏览器对象模型

    l对象的角色,因此所有在全局作用域中声明的变量/函数都会变成window对象的属性和方法; // PS:尝试访问未声明的变量会抛出错误,但是通过查询window对象,可以知道某个可能未声明的对象是否存 ...

  3. paip.python NameError name 'xxx' is not defined\

    paip.python NameError name 'xxx' is not defined\ 导入一个另一个文件里面的函数的时候儿,出孪这个err #这个仅仅导入孪file...要使用里面的fun ...

  4. 从头学Android之Android布局管理:LinerLayout线性布局

    LinerLayout线性布局: 这种布局方式是指在这个里面的控件元素显线性,我们可以通过setOrientation(int orientation)来指定线性布局的显示方式,其值有:HORIZON ...

  5. 已知2个一维数组:a[]={3,4,5,6,7},b[]={1,2,3,4,5,6,7};把数组a与数组b 对应的元素乘积再赋值给数组b,如:b[2]=a[2]*b[2];最后输出数组b的元素。

    package hanqi; import java.util.Scanner; public class Test7 { public static void main(String[] args) ...

  6. GTD中定位篇

    一:为什么要定位? 每天我们的大脑涌现很多想法和要处理很多事情,如果我们没有一套流模式处理这些想法和事情,我们大脑将会处于混战忙碌中,很快就被淹没. 定位的目的: 就是有一套流模式有序的分界我们想法和 ...

  7. windows批处理

    1.日期作为变量当做文件名的一部分. C:\Documents and Settings\Simon>echo %date%2008-09-09 星期二 C:\Documents and Set ...

  8. 【转】Java之WeakReference与SoftReference使用讲解

    Java 2 平台引入了 java.lang.ref 包,其中包括的类可以让您引用对象,而不将它们留在内存中.这些类还提供了与垃圾收集器(garbage collector)之间有限的交互. 1.先“ ...

  9. ASP.NET MVC中的模型装配 封装方法 非常好用

    下面说一下 我们知道在asp.net mvc中 视图可以绑定一个实体模型 然后我们三层架构中也有一个model模型 但是这两个很多时候却是不一样的对象来的 就拿微软的官方mvc例子来说明 微软的视图实 ...

  10. Oracle 11g RAC环境下Private IP修改方法及异常处理

    Oracle 11g RAC环境下Private IP修改方法及异常处理 Oracle 11g RAC环境下Private IP修改方法及异常处理 一. 修改方法 1. 确认所有节点CRS服务以启动 ...