实现头像的上传

jsp:

上传jsp上的头像

<div class="factoryLogo">
  					<img <c:if test="${sessionFactory.factoryLogo == null}">src="static/img/factoryHeader.jpg"</c:if>
  						 <c:if test="${sessionFactory.factoryLogo != null}">src="factory/imageShowSimple?seq=${sessionFactory.factoryLogo}"</c:if> 
  						 class="img-rounded" id="headerPic">
 						<a id="portraitUpload" href="#" οnclick="return false;">上传企业logo</a>
 						<input id="portraitFile" type="file" name="portraitFile" οnchange="portraitFileUpload()"/>
  			</div>

在js中:

实现portraitFileUpload

function imgCheck(filepath){
    var extStart = filepath.lastIndexOf(".");
    var ext = filepath.substring(extStart, filepath.length).toUpperCase();
    if (ext != ".PNG" && ext != ".JPG") {
        showMessage("图片只支持png,jpg格式");
        return false;
    }
    return true;
}

-----------------------------------------------------------------------------------------------------------

function portraitFileUpload(){

		if(!imgCheck($("#portraitFile").val())){
			return false;
		}
		$.ajaxFileUpload({
			type: "POST",
			url:'factory/uploadPortrait',
			secureuri:false,
			fileElementId:'portraitFile',
			dataType: 'json',
			success: function(data,status){
				 if(data.result == "success"){
					 if(data.imgSeq != null){
						 $("#headerPic").attr("src","factory/imageShowSimple?seq="+data.imgSeq);
					 }
					 $(window.parent.document).contents().find("#touxiangWelcomeImg").attr("src", "factory/imageShowSimple?seq="+data.imgSeq);
					 showMessage("头像上传成功");
				 } else {
					 showMessage("头像" + data.result);
				 }
				$("#portraitFile").replaceWith('<input id="portraitFile" name="portraitFile" type="file" οnchange="portraitFileUpload()"/>');
			},
	        error: function(data,status,e){
	        	showMessage("头像上传异常");
	        }
		});
}

controller:

@RequestMapping("uploadPortrait")
	@ResponseBody
	public Object uploadPortrait(HttpSession httpSession,HttpServletRequest request) throws IOException {
		logBefore(logger, "factory/uploadPortrait");

	    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
	    MultipartFile file = multipartRequest.getFile("portraitFile");// 获取上传文件名  
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    byte[] imgWeb = new byte[(int)file.getSize()];
	    imgWeb = file.getBytes();
	    
	    int size = file.getInputStream().available() / 1024;
	    
	    // 大于8M不予受理
	    if(size > 8 * 1024){
	    	map.put("result", "图片文件不得大于8M");
	    	return JSON.toJSONString(map,true);
	    }
	    
	    imgWeb = imgWebCompress(size,request,file,map,imgWeb);
	    
	    FactoryFactoryInfo factoryInfo = (FactoryFactoryInfo) request.getSession().getAttribute(
				Const.SESSION_FACTORY);
	    String factoryId = String.valueOf(factoryInfo.getFactoryId());
	 
	    //上传图片 调用接口保存头像以及获取头像ID
	    UploadPictureParam picParam = new UploadPictureParam();
	    UploadPictureResult picResult = new UploadPictureResult();
	    
	    picParam.setFactoryId(String.valueOf(factoryId));
	    picParam.setDifferent(FactoryConsts.STRING_WEB_ONE);//web
	    picParam.setDiffPicture(FactoryConsts.CHAR_PIC_HEAD);//头像
	    picParam.setImgWeb(imgWeb);
	    picParam.setPictureName("portraitFile");
	    
	    picResult = factoryInfoService.uploadPicture(picParam);
	    //String imgSeq = null;
	    
	    if(picResult != null && "0".equals(picResult.getResult())){
	    	//获取企业头像地址
	    	WriteFactoryPictureParam wfpParam = new WriteFactoryPictureParam();
			wfpParam.setFactoryId(factoryId);
			wfpParam.setPostfix("JPG");
			WriteFactoryPictureResult wfpResult = new WriteFactoryPictureResult();
			wfpResult = jobInfoService.writeFactoryPicture(wfpParam);
			//企业头像地址
			String url = "";
			if(wfpResult != null && "0".equals(wfpResult.getResult())){
				url = wfpResult.getUrl();
			}
			FactorySaveBaseInfoParam UpParam = new FactorySaveBaseInfoParam();
			FactorySaveBaseInfoResult UpResult = new FactorySaveBaseInfoResult();
			UpParam.setFactoryId(Long.valueOf(factoryId));
			UpParam.setFactoryLogoPath(url);
			UpParam.setUpdateUser(factoryId);
			UpParam.setKbn("3");
			UpResult = factoryInfoService.updateFactoryInfo(UpParam);
			
	    	//获取头像ID
	    	FactoryFactoryInfoParam infoParam = new FactoryFactoryInfoParam();
	    	FactoryFactoryInfoResult infoResult = new FactoryFactoryInfoResult();
			infoParam.setFactoryId(String.valueOf(factoryId));
			infoParam.setDifferent(FactoryConsts.STRING_WEB_ONE); //web
			infoResult = factoryInfoService.factoryInfo(infoParam);
			
			map.put("imgSeq", String.valueOf(infoResult.getFactoryInfoEx().getFactoryLogo()));
			
			httpSession.setAttribute(Const.SESSION_FACTORY, infoResult.getFactoryInfoEx());
			
			map.put("result", "success");
	    }else{
	    	map.put("result", "上传图片失败");
	    }
	    return JSON.toJSONString(map,true);
	}

/**
	 * 图片压缩
	 * 
	 * @param 
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
	private byte[] imgWebCompress(int size,HttpServletRequest request,MultipartFile file,Map<String, Object> map,byte[] imgWeb) throws IOException{
		    
		    // 大于100K压缩
		    if(size > FactoryConsts.INT_100){
		    	
		    	CommonsMultipartFile cf= (CommonsMultipartFile)file; 
		    	
		    	DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
		    	
		        File oldFile = fi.getStoreLocation();
		    	// 创建新的文件
		    	String path = request.getSession().getServletContext().getRealPath("/") + "files" + File.separator + "temp" + File.separator;
		    	
		    	File newZipFile = new File(path + String.valueOf(System.currentTimeMillis()) + ".jpg");   
		    	
		    	if (!newZipFile.exists()) {
					newZipFile.createNewFile();
		    	}
		    	
		    	FactoryImageZipService.zipImageFile(oldFile, newZipFile, 600, 600);
		    
		    	imgWeb = getImageFileByte(newZipFile);
		    }else{
		    	
		    	imgWeb = new byte[(int)file.getSize()];
		    	
			    imgWeb = file.getBytes();
		    }
		    return imgWeb;
	}
	
	/**
	 * 获取图片文件的数组
	 * 
	 * @param filePath
	 * @return
	 */
	@SuppressWarnings("finally")
	private byte[] getImageFileByte(File file){
		
		FileInputStream fin = null;
		
		byte[] content = null;
		
		try {
			fin = new FileInputStream(file);
			ByteBuffer nbf = ByteBuffer.allocate((int) file.length());
	        byte[] array = new byte[1024];
	        int length = 0;
			while ((length = fin.read(array)) > 0) {
				if (length != 1024) {
					nbf.put(array, 0, length);
				} else {
					nbf.put(array);
				}
			}
			// 图片数组
			content = nbf.array();
		} catch (FileNotFoundException e) {
			logger.info("文件不存在");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("文件读写异常");
			e.printStackTrace();
		} finally {
			// 关闭流
			try {
				if (fin != null) {
					fin.close();
				}
			} catch (IOException e) {
				logger.info("文件关闭异常");
				e.printStackTrace();
			} finally{
				// 删除临时文件
				if(file.exists()){
					file.delete();
				}
				return content;
			}
		}
	}

FactoryImageZipService文件调用

package service.factory;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;

import org.springframework.web.multipart.MultipartFile;

public class FactoryImageZipService { 
   
    /**
     * 等比例压缩图片文件<br> 先保存原文件,再压缩、上传
     * @param oldFile  要进行压缩的文件
     * @param newFile  新文件
     * @param width  宽度 //设置宽度时(高度传入0,等比例缩放)
     * @param height 高度 //设置高度时(宽度传入0,等比例缩放)
     * @param quality 质量
     * @return 返回压缩后的文件的全路径
     */ 
    public static String zipImageFile(File oldFile, File newFile, int width, int height) { 
        if (oldFile == null) { 
            return null;
        } 
        try { 
            /** 对服务器上的临时文件进行处理 */ 
            BufferedImage srcFile = ImageIO.read(oldFile);
            
            // 判断图片背景是否为透明
			if (srcFile.getTransparency() == Transparency.TRANSLUCENT) {
				// 去掉透明背景,设置为白色
				srcFile = get24BitImage(srcFile, Color.WHITE);
			}
            // 原图片宽
            int oldImageWidth = srcFile.getWidth(null);
            // 原图片高
            int olgImageHight = srcFile.getHeight(null);
            // 图片比率
            double imageRate;
            
			if (width > 0) {
				imageRate = width / (double) oldImageWidth;
				height = (int) (olgImageHight * imageRate);
			} else {
				if (height > 0) {
					imageRate = height / (double) olgImageHight;
					width = (int) (oldImageWidth * imageRate);
				}
			}
            /** 宽,高设定 */ 
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            
			tag.getGraphics().drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            
            /** 压缩之后临时存放位置 */ 
            FileOutputStream out = new FileOutputStream(newFile);
   
            ImageIO.write(tag,  "jpeg" , new File(newFile.getPath()));
            
            out.flush();
            out.close();
   
        } catch (FileNotFoundException e) { 
            e.printStackTrace();
        } catch (IOException e) { 
            e.printStackTrace();
        } 
        return newFile.getAbsolutePath();
    } 
   
    /**
     * 按宽度高度压缩图片文件<br> 先保存原文件,再压缩、上传
     * @param oldFile  要进行压缩的文件全路径
     * @param newFile  新文件
     * @param width  宽度
     * @param height 高度
     * @param quality 质量
     * @return 返回压缩后的文件的全路径
     */ 
    public static void zipWidthHeightImageFile(Image image,File newFile, int width, int height) { 
        if (image == null) {
            return;
        } 
        try { 
            /** 宽,高设定 */ 
            BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(image, 0, 0, width, height, null);   
            /** 压缩之后临时存放位置 */ 
            FileOutputStream out = new FileOutputStream(newFile);
   
            ImageIO.write(tag, "jpg", out);
            
            
            out.close();
	    } catch (FileNotFoundException e) { 
	            e.printStackTrace();
	    } catch (IOException e) { 
	            e.printStackTrace();
	    } 
    }
    
    /**
     * 根据质量和宽高压缩图片
     * 
     * @param file
     * @param newFile
     */
    public static void zipQualityImageFile(MultipartFile file, File newFile) { 
    	// 如果文件为NULL返回
    	if (file == null) {
    		return;
    	}
    	try { 
    		Image image = ImageIO.read(file.getInputStream());
	    	int w = image.getWidth(null);
	    	int h = image.getHeight(null);
	    	int width = (int)(0.3 * w);
	    	int height = (int)(0.3 * h);
    		
    		/** 宽,高设定 */ 
	    	
	    	double rate1 = ((double) image.getWidth(null)) / (double) width + 0.1;   
            double rate2 = ((double) image.getHeight(null)) / (double) height + 0.1;   
            // 根据缩放比率大的进行缩放控制   
            double rate = rate1 > rate2 ? rate1 : rate2;   
            int newWidth = (int) (((double) image.getWidth(null)) / rate);   
            int newHeight = (int) (((double) image.getHeight(null)) / rate); 
	    	
    		BufferedImage tag = new BufferedImage(newWidth, newHeight,BufferedImage.TYPE_4BYTE_ABGR);
    		
			for (int i = 0; i < newWidth; i++) {
				for (int j = 0; j < newHeight; j++) {
					int rgb = tag.getRGB(i, j);
					if (isBackPixel(rgb)) {
						tag.setRGB(i, j, 0);
					}
				}
			}
    		
    		tag.getGraphics().drawImage(image, 0, 0, newWidth, newHeight, null); 
    		/** 压缩之后临时存放位置 */ 
    		FileOutputStream out = new FileOutputStream(newFile);
    		// 指定写图片的方式为 jpg  
    		ImageWriter imgWrier = ImageIO.getImageWritersByFormatName("png").next();  
    		
    		ImageWriteParam imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);  
            // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT  
            imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);  
            // 将压缩质量设置为 0 和 1 之间的某个值。  
            imgWriteParams.setCompressionQuality((float)0.1);  
            // 指定 writer 使用逐步模式写出图像,从而输出流将包含一系列质量递增的扫描。
            imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED); 
            ColorModel colorModel = ColorModel.getRGBdefault();  
            // 指定压缩时使用的色彩模式  
            imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel  
                    .createCompatibleSampleModel(width, height)));  
            imgWrier.reset();  
            // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造  
            imgWrier.setOutput(ImageIO.createImageOutputStream(out));  
            // 调用write方法,就可以向输入流写图片  
            imgWrier.write(null, new IIOImage(tag, null, null), imgWriteParams);  
    		
    		out.close();
    	} catch (FileNotFoundException e) { 
    		e.printStackTrace();
    	} catch (IOException e) { 
    		e.printStackTrace();
    	} 
    }
    
    /**
     * 判断当前像素是否为黑色不透明的像素(-16777216)
     * @param pixel 要判断的像素
     * @return 是背景像素返回true,否则返回false
     */
	private static boolean isBackPixel(int pixel) {
		int back[] = { -16777216 };
		for (int i = 0; i < back.length; i++) {
			if (back[i] == pixel){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 去掉PNG的透明背景设置为白色
	 * 
	 * @param image
	 * @param bgColor
	 * @return
	 */
    private static BufferedImage get24BitImage(BufferedImage image, Color bgColor) {
        
    	int width = image.getWidth();
        
        int height = image.getHeight();
        
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        
        Graphics2D graphic = newImage.createGraphics();
        
        graphic.setColor(bgColor);
        
		graphic.fillRect(0, 0, width, height);
        
		graphic.drawRenderedImage(image, null);
        
        graphic.dispose();
        
        return newImage; 
    }
}

文件图片的上传就OK了,接下来是图片的显示

jsp页面中的  src="factory/imageShowSimple?seq=${sessionFactory.factoryLogo}

package controller.factory;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import model.factory.base.FactoryImageInfo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import service.factory.FactoryImageInfoService;
import controller.base.BaseController;

@Controller
public class FactoryImageDisplayControll extends BaseController{
	
	@Resource
	private FactoryImageInfoService factoryImageInfoService;

	@RequestMapping("factory/imageShowSimple")
	public void imageShowSimple(HttpServletResponse response, String seq){
		
		FactoryImageInfo imageInfo = null;
		
		ServletOutputStream output = null;
		
		try {
			// 查询图片信息表
			if(seq != null && !"".equals(seq)){
				imageInfo = factoryImageInfoService.selectByPrimaryKey(Integer.parseInt(seq));
			}
			// 将图片写入画面
			if(imageInfo != null){
				
				output=response.getOutputStream();

				byte[] imageBytes = imageInfo.getImageBlob();
				
				output.write(imageBytes);
			}
		} catch (IOException e) {
			logger.info("操作失败");
			e.printStackTrace();
		} catch (Exception e) {
			logger.info("转化失败");
			e.printStackTrace();
		} finally{
			try {
				if(output != null){
					output.close();
				}
			} catch (IOException e) {
				logger.info("数据流关闭异常");
				e.printStackTrace();
			}
		}
		
	}
}

结束~








  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值