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. 近期code review几处小问题集锦

    1 线程池使用不当 我们的调度系统需要将一堆会员分配给相应的人员来处理,流程如以下伪代码所示: public void dispatch() { while (true) { List<Memb ...

  2. paip.代码生成器数据源格式最佳实践

    paip.代码生成器数据源格式最佳实践 需要满足几个条件. 1.基于文本 2.容易的编辑.. 3,容易的代码解析. 这样,常用的设计工具powerdesign cdm pdm就排除兰...cdm虽然是 ...

  3. paip.判断文件是否存在uapi python php java c#

    paip.判断文件是否存在uapi python php java c# ==========uapi file_exists exists() 面向对象风格:  File.Exists 作者: 老哇 ...

  4. NXP LPC 状态可配置的定时器(SCT)

    状态可配置的定时器(SCT) 前言正在申请专利的状态可配置的定时器(SCT),是一个复杂的,但易于配置的定时器,它提供前所未有的灵活性,使工程师们在未来证明他们的设计,并减少进入市场的时间.在其最简单 ...

  5. gridlaylout 简单布局

    package com.example.gridlayout; import android.app.Activity; import android.os.Bundle; import androi ...

  6. 【Android开发坑系列】如何让Service尽可能存活

    流行的思路如下[2015-11-20更新]: 1.让Service杀不死.Service的onStartCommand返回START_STICKY,同时onDestroy里面调用startServic ...

  7. linux下IM server搭建

    一步一步开始做. 附录: 一套开源协议:http://www.igniterealtime.org/index.jsp Proso:http://prosody.im/ 那谁网友的笔记http://w ...

  8. js 去掉字符串前面的0

    <script>var a='00123';alert(a.replace(/\b(0+)/gi,""));</script>

  9. 超体.特效中英字幕.Lucy.2014.BD1080P.X264.AAC.English&Mandarin.CHS-ENG

    资源名称 其它信息 资源大小 BT下载 超体.Lucy.2014.BD-MP4-原创翻译中英双语字幕.mp4 seeders: / leechers: 511.15MB 下载 [飘域家园]移动迷宫.T ...

  10. Linux之重定向

    Linux重定向是指修改原来默认的一些东西,对原来系统命令的默认执行方式进行改变,比如说简单的我不想看到在显示器的输出而是希望输出到某一文件中就可以通过Linux重定向来进行这项工作. Linux默认 ...