jsp实现文件上传(一)用jspSmartUpload组件实现文件上传
java类(ImageUtil.java)
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.imageio.ImageIO; public class ImageUtil { private BufferedImage i = null; /* * 上传图片 * */ public void setImg(String imgpath) { try { this.i = ImageIO.read(new FileInputStream(imgpath)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public ImageUtil() { } public ImageUtil(String imgpath) { try { this.i = ImageIO.read(new FileInputStream(imgpath)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /* * 图片加水印文字 * */ public void txt(String s, int fontsize, String imgpath) { Graphics g = this.i.getGraphics(); g.setFont(new Font("隶书", Font.BOLD, fontsize)); // g.setColor(Color.RED); g.setColor(new Color(255, 255, 255, 80)); g.drawString(s, i.getWidth() - 200, this.i.getHeight() - fontsize - 10); try { ImageIO.write(this.i, "jpg", new File(imgpath)); } catch (IOException e) { e.printStackTrace(); } } /* * 图片加水印logo * */ public void logo(String logopath, String imgpath) { Graphics g = this.i.getGraphics(); try { BufferedImage logo = ImageIO.read(new File(logopath)); g.drawImage(logo, this.i.getWidth() - 189 - 10, this.i.getHeight() - 69 - 10, this.i.getWidth() - 10, this.i.getHeight() - 10, 0, 0, logo.getWidth(), logo.getHeight(), null); ImageIO.write(this.i, "jpg", new File(imgpath)); } catch (IOException e) { e.printStackTrace(); } }
/* * 缩略图 * */
public void thumd(int ww, int hh, String imgpath) { int w = this.i.getWidth(); int h = this.i.getHeight(); BufferedImage nimg = new BufferedImage(ww, hh, BufferedImage.TYPE_INT_RGB); Graphics g = nimg.getGraphics(); g.drawImage(this.i, 0, 0, ww, hh, 0, 0, w, h, null); try { ImageIO.write(nimg, "jpg", new File(imgpath)); } catch (IOException e) { e.printStackTrace(); } } }
使用上传照片在jsp中使用
SmartUpload su = new SmartUpload(); su.initialize(pageContext); su.upload(); ImageUtil iu = new ImageUtil(); for(int i=0;i<su.getFiles().getCount();i++){ File f = su.getFiles().getFile(i); if(f.isMissing()){ continue; } UUID u = UUID.randomUUID(); String path = "/upload/"+u.toString()+"."+f.getFileExt(); f.saveAs(path); String pp = request.getServletContext().getRealPath(path); iu.setImg(pp); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。