jsp实现图片上传压缩添加水印

飘醉雪舞 贡献于2012-05-11

作者 微软用户  创建于2011-07-28 06:41:00   修改者微软用户  修改于2011-07-28 06:59:00字数12931

文档摘要:主要实现:上传文件类型的前台验证,后台验证上传文件的类型、格式;实现图片的压缩和添加水印等功能。
关键词:

Struts1实现文件上传功能 实现技术:Struts1.3+JSP 主要实现:上传文件类型的前台验证,后台验证上传文件的类型、格式;实现图片的压缩和添加水印等功能。 JSP页面部分代码: (1)上传表单代码
* 只允许上传gif、jpg、bmp、png! 
(2)JavaScript验证代码 (3)/WEB-INF/UI/success.jsp代码 ${suc } 点击返回 (4)/WEB-INF/UI/fail.jsp代码 操作失败!${message } 单击返回前一页  Struts1中配置文件的配置 后台代码 (1)Domain Object    package com; import java.io.File; import java.io.FileOutputStream; import java.util.Arrays; import java.util.List; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class ImageForm extends ActionForm { /** 图片路径 * */ private FormFile imagename; public FormFile getImagename() { return imagename; } public void setImagename(FormFile imagename) { this.imagename = imagename; } //验证上传图片的格式和类型 public static boolean validateImageFileType(FormFile formFile) { if (formFile != null && formFile.getFileSize() > 0) { // 获取上传文件的后缀 String ext = formFile.getFileName().substring( formFile.getFileName().lastIndexOf('.') + 1).toLowerCase(); //允许上传的文件类型 List arrowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg"); //允许上传的文件后缀 List arrowExtension = Arrays.asList("gif","jpg","bmp","png"); return arrowType.contains(formFile.getContentType().toLowerCase())&&arrowExtension.contains(ext); } return true; } /**获取上传文件的后缀*/ public static String getExt(FormFile formfile){ return formfile.getFileName().substring(formfile.getFileName().lastIndexOf('.')+1).toLowerCase(); } /** * 保存文件 * @param savedir 存放目录 * @param fileName 文件名称 * @param data 保存的内容 * @return 保存的文件 * @throws Exception */ public static File saveFile(File savedir, String fileName, byte[] data) throws Exception{ if(!savedir.exists()) savedir.mkdirs();//如果目录不存在就创建 File file = new File(savedir, fileName); FileOutputStream fileoutstream = new FileOutputStream(file); fileoutstream.write(data); fileoutstream.close(); return file; } } (2)Action文件的内容 package com.action; import java.awt.Color; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.apache.struts.upload.FormFile; import com.ImageForm; import com.util.ImageSizer; import com.util.WarterImage; public class UploadAction extends DispatchAction { /** * 添加图片 */ public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ImageForm image = (ImageForm) form; // 获取到页面中传输过来的文件 FormFile file = image.getImagename(); if (!ImageForm.validateImageFileType(file)) { request.setAttribute("message", "文件格式不正确,只允许上传gif/jpg/png/bmp图片"); return mapping.findForward("fail"); } // 判断传过来的数据是否为空,如果为空,返回页面 if (null != file.getFileName() && file.getFileSize() > 0 && file.getFileSize() < 204800) { // 我们要生成一个文件路径,我们应该把上传的文件放到一个文件夹内,路径第一如下upfile/images/2011/X/x/sss.xx SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/"); String fileUrlDir = "/upfile/images/" + sdf.format(new Date()); //得到图片保存目录的真实路径 String fileUrl = request.getSession().getServletContext() .getRealPath(fileUrlDir) + "\\"; System.out.println(fileUrl); String ext = ImageForm.getExt(file); String imagename = UUID.randomUUID().toString() + "." + ext;//构建文件名称 ImageForm .saveFile(new File(fileUrl), imagename, file.getFileData()); // 文件保存到服务器上的路径 String imagePro = fileUrl + imagename; // 对图片进行压缩,如果传过来的数据为0,则使用默认值 ImageSizer.resize(new File(imagePro), new File(imagePro), 120, ext); // 添加水印,这个路径要选择服务器的路径,保存要和保存图片的路径一致 WarterImage.pressText("添加水印", imagePro, "宋体", 0, Color.black, 10, 0, 0); request.setAttribute("suc", "图片保存成功"); return mapping.findForward("success"); } // 判断图片不能太大 else if (null != file.getFileName() && file.getFileSize() > 0) { request.setAttribute("message", "提交图片不能超过200k"); return mapping.findForward("fail"); } return mapping.findForward("fail"); } } 图片压缩和添加水印类 (1)图片压缩 package com.util; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * 图像压缩工具 * */ public class ImageSizer { public static final MediaTracker tracker = new MediaTracker(new Component() { private static final long serialVersionUID = 1234162663955668507L;} ); /** * @param originalFile 原图像 * @param resizedFile 压缩后的图像 * @param width 图像宽 * @param format 图片格式 jpg, png, gif(非动画) * @throws IOException */ public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if(format!=null && "gif".equals(format.toLowerCase())){ resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage( in ); waitForImage( inputImage ); int imageWidth = inputImage.getWidth( null ); if ( imageWidth < 1 ) throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" ); int imageHeight = inputImage.getHeight( null ); if ( imageHeight < 1 ) throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" ); // Create output image. int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >=0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT); checkImage( outputImage ); encode(new FileOutputStream(resizedFile), outputImage, format); } /** Checks the given image for valid width and height. */ private static void checkImage( Image image ) { waitForImage( image ); int imageWidth = image.getWidth( null ); if ( imageWidth < 1 ) throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" ); int imageHeight = image.getHeight( null ); if ( imageHeight < 1 ) throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" ); } /** Waits for given image to load. Use before querying image height/width/colors. */ private static void waitForImage( Image image ) { try { tracker.addImage( image, 0 ); tracker.waitForID( 0 ); tracker.removeImage(image, 0); } catch( InterruptedException e ) { e.printStackTrace(); } } /** Encodes the given image at the given quality to the output stream. */ private static void encode( OutputStream outputStream, Image outputImage, String format ) throws java.io.IOException { int outputWidth = outputImage.getWidth( null ); if ( outputWidth < 1 ) throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" ); int outputHeight = outputImage.getHeight( null ); if ( outputHeight < 1 ) throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" ); // Get a buffered image from the image. BufferedImage bi = new BufferedImage( outputWidth, outputHeight, BufferedImage.TYPE_INT_RGB ); Graphics2D biContext = bi.createGraphics(); biContext.drawImage( outputImage, 0, 0, null ); ImageIO.write(bi, format, outputStream); outputStream.flush(); } /** * 缩放gif图片 * @param originalFile 原图片 * @param resizedFile 缩放后的图片 * @param newWidth 宽度 * @param quality 缩放比例 (等比例) * @throws IOException */ private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException { if (quality < 0 || quality > 1) { throw new IllegalArgumentException("Quality has to be between 0 and 1"); } ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath()); Image i = ii.getImage(); Image resizedImage = null; int iWidth = i.getWidth(null); int iHeight = i.getHeight(null); if (iWidth > iHeight) { resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH); } else { resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH); } // This code ensures that all the pixels in the image are loaded. Image temp = new ImageIcon(resizedImage).getImage(); // Create the buffered image. BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB); // Copy image to buffered image. Graphics g = bufferedImage.createGraphics(); // Clear background and paint the image. g.setColor(Color.white); g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null)); g.drawImage(temp, 0, 0, null); g.dispose(); // Soften. float softenFactor = 0.05f; float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0}; Kernel kernel = new Kernel(3, 3, softenArray); ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); bufferedImage = cOp.filter(bufferedImage, null); // Write the jpeg to a file. FileOutputStream out = new FileOutputStream(resizedFile); // Encodes image as a JPEG data stream JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage); param.setQuality(quality, true); encoder.setJPEGEncodeParam(param); encoder.encode(bufferedImage); } } (2)添加水印 package com.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class WarterImage { public WarterImage() { } /** * * 把图片印刷到图片上 * * @param pressImg -- * 水印文件 * @param targetImg -- * 目标文件 * @param x * --X坐标 * @param y * --y坐标 */ public final static void pressImage(String pressImg, String targetImg, int x, int y) { try { // 目标文件 File _file = new File(targetImg); Image src = ImageIO.read(_file); // 获取图片的宽度 int wideth = src.getWidth(null); // 获取图片的高度 int height = src.getHeight(null); BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(src, 0, 0, wideth, height, null); // 水印文件 File _filebiao = new File(pressImg); Image src_biao = ImageIO.read(_filebiao); // 获取水印图片的宽度 int wideth_biao = src_biao.getWidth(null); // 获取水印图片的高度 int height_biao = src_biao.getHeight(null); // 如果传输过来的坐标值为x==-1,y==-1,则水印图片添加到左下角 if (x == -1 && y == -1) { g.drawImage(src_biao, wideth - wideth_biao, height - height_biao, wideth_biao, height_biao, null); } else { g.drawImage(src_biao, x, y, wideth_biao, height_biao, null); } // 水印文件结束 g.dispose(); FileOutputStream out = new FileOutputStream(targetImg); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } catch (Exception e) { e.printStackTrace(); } } /*************************************************************************** * 打印文字水印图片 * * @param pressText * --文字 * @param targetImg -- * 目标图片 * @param fontName -- * 字体名 * @param fontStyle -- * 字体样式 * @param color -- * 字体颜色 字体大小 * @param x * x坐标轴 * @param y * y坐标轴 */ public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x, int y) { try { System.out.println(targetImg); File _file = new File(targetImg); Image src = ImageIO.read(_file); int wideth = src.getWidth(null); int height = src.getHeight(null); BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(src, 0, 0, wideth, height, null); if (color == null) { g.setColor(Color.black); } else { g.setColor(color); } g.setFont(new Font(fontName, fontStyle, fontSize)); // 判断输入的是中文还是英文,因为英文和中文所占的像素比例不一样,所以需要设置一下,美观漂亮 byte[] bytes = pressText.getBytes(); int i = bytes.length;// i为字节长度 int j = pressText.length();// j为字符长度 // 如果i==j 说明是英文字符 if (i == j) { g.drawString(pressText, (int) (wideth - (fontSize * (pressText.length() / 2.0)) - x), height - y); } else { g.drawString(pressText, (int) (wideth - (fontSize * pressText.length()) - x), height - y); } g.dispose(); FileOutputStream out = new FileOutputStream(targetImg); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } catch (Exception e) { System.out.println(e); } } }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 8 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档