Java将图片压缩并以base64方式保存数据库
Java将图片压缩并以base64方式保存数据库
Alexdevlin 发表于1年前
Java将图片压缩并以base64方式保存数据库
  • 发表于 1年前
  • 阅读 13
  • 收藏 0
  • 点赞 0
  • 评论 0

【腾讯云】如何购买服务器最划算?>>>   

1.页面`

<span  id="uploadImg" style="margin:50px;background-color:#ddd;display:inline-block;height:130px;width:200px;">
<span  style="color:#bbb;font-weight:600;border:2px #ccc dashed;font-size:20px;text-align:center;display:inline-block;height:50px;width:50px;line-height:50px;position:absolute;margin-top:40px;margin-left:75px;z-index:99">+</span>
 <img id="preview"   style="display: none; ">	</span>
<input type="file" style="display:none" name="ImgCard" id="imgFileBtn" id="imgFileBtn" style="width:150px;" onchange="javascript:setImagePreview();"/>
</div>

2.后台

        private File ImgCard;
	private String ImgCardContentType;
	private String ImgCardFileName;  
	public String tjMoneyCert(){
		try{
				int userID = (Integer)this.getSession().getAttribute("userID");
				String userName = (String)this.getSession().getAttribute("userName");
				String userIP = null;
				userIP = RealIP.xffIP(this.getRequest().getHeader("X-Forwarded-For"));
				if(userIP == null || userIP.length() == 0){
					userIP = this.getRequest().getRemoteAddr();
				};
				UserMoneyCert userMoneyCert = new UserMoneyCert();
				userMoneyCert.setUserID(userID);
				userMoneyCert.setUserName(userName);
				userMoneyCert.setCreator(userName);
				userMoneyCert.setUserIP(userIP);
		                boolean isImage = false;  
		                String[] imgExts = {".jpg", ".jpeg",".bmp", ".png"};  
		                for(String ext : imgExts) {  
		                  if(ImgCardFileName.toLowerCase().endsWith(ext)) {  
		            	     isImage = true;  
		                     break;  
		                }  
		            }  
		        if((ImgCard.length()/1024/1024)>3){
		        	return ERROR;
		        }
		        String artwork=  getPic(ImgCard);
		        File f= compressPic(ImgCard);
		        String img= getPic(f);
			    userMoneyCert.setArtwork(img);//压缩后的图
		        userMoneyCert.setImg(artwork);//原图
				Integer num=this.getBusinessService().insertUserMoneyCert(userMoneyCert);
				return SUCCESS;
		}catch(Exception e){
			LOGGER.error(e.getMessage());
			return ERROR;
		}
	}

        public String getPic(File f) throws IOException{
		BASE64Encoder encoder = new BASE64Encoder();    
        BufferedImage bi;
        String img=null;
		bi = ImageIO.read(f);    
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        String imageType = getExtention(ImgCardFileName).replace(".", "");
		ImageIO.write(bi, imageType, baos);
		byte[] bytes = baos.toByteArray();    
		img = encoder.encodeBuffer(bytes).trim();  
        return img;
		
	}

    public File  compressPic(File file) throws Exception{
		int filesize = 0;
		File targetFile=null;
		if(file!=null){
			filesize = Integer.parseInt(String.valueOf((file.length() / 1024)));
		}
		//创建压缩后的文件名路径
		String imageType = getExtention(ImgCardFileName).replace(".", "");
		String realName = DBKeyCreator.getRandomKey(12) +"."+ imageType;
		//开始图片压缩
		boolean compressFlag = this.compressPicNew(file, realName, 300, imageType);
		//压缩成功
		if(compressFlag){
			//获取压缩后的文件
			 targetFile = new File(realName);
		}
		return targetFile;
	}

	private static String getExtention(String fileName) {
		int pos = 0;
		pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

/**
	 * 压缩图片
	 * @param srcFile    源文件
	 * @param descFilePath	 目标文件地址
	 * @param maxSize		 指定要压缩到多大 单位:K
	 * @param imageType	     源文件格式
	 * @return
	 * @throws IOException
	 */
	public  boolean compressPicNew(File file, String descFilePath,int maxSize,String imageType)     throws IOException {
       
        BufferedImage srcImage = null;
        FileOutputStream out = null;
        ImageWriter imgWrier = null;
        try {
        	Boolean isZipSuccess = false;
            System.out.println("原文件大小:"+file.length());
            //读取源文件
            srcImage = ImageIO.read(file);
            //先进行质量压缩
            BufferedImage targetImage = new         BufferedImage(srcImage.getWidth(),srcImage.getHeight(),BufferedImage.TYPE_USHORT_555_RGB);
            Graphics2D g2d = targetImage.createGraphics();
            isZipSuccess = g2d.drawImage(srcImage,0,0,null);
             if(isZipSuccess){
            	imgWrier = ImageIO.getImageWritersByFormatName(imageType).next();
                //输出图片
	              out = new FileOutputStream(descFilePath);
	              imgWrier.reset();
                  imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                // 调用write方法,就可以向输入流写图片
                  imgWrier.write(targetImage);
                  out.flush();
                	out.close();
             }else{
            	 //质量压缩失败直接返回
            	 isZipSuccess =false;
            	 return isZipSuccess;
             }
             
             //尺寸压缩
             int i = 1;
        	 while(true){
        		
        		 File srcScaleFile = new File(descFilePath);
            	 long srcScaleFileSize = srcScaleFile.length();

            	 if(srcScaleFileSize>maxSize*512){
            		 
            		 //每次宽度降低10%等比例压缩
            		 BufferedImage srcScaleImage = ImageIO.read(srcScaleFile);
            		 int oldWidth = srcScaleImage.getWidth();
            		 int oldHeight = srcScaleImage.getHeight();
            		 
            		
            		 int newWidth = (int)(0.9 * (double)oldWidth);
            		 int newHeight = (int)(((double)oldHeight/(double)oldWidth)*newWidth);
            		 //计算新的宽和高
            		 if(i==40 || newWidth==0){				//尺寸压缩10次,尝试10次还是达不到300K一下就当作压缩失败
            			 isZipSuccess = false;
            			 break;
            		 }
            		 i++;
            		 
            		 BufferedImage targetScaledImage = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_USHORT_555_RGB);
            		 isZipSuccess= targetScaledImage.getGraphics().drawImage(srcScaleImage,0,0,newWidth,newHeight,null); 
                     
                     if(isZipSuccess){
                         // 调用write方法,就可以向输入流写图片
                    	 imgWrier = ImageIO.getImageWritersByFormatName(imageType).next();
                    	 //输出图片
        	             out = new FileOutputStream(descFilePath);
        	             imgWrier.reset();
                         imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                         // 调用write方法,就可以向输入流写图片
                         imgWrier.write(targetScaledImage);
                         out.flush();
                         out.close();
                      }else{
                    	  isZipSuccess = false;
                    	  break;
                      }
            	 }else{
            		 break;
            	 }
        	 }
           
            return isZipSuccess;

        } catch (Exception e) {
        	if(null != out){
                out.close();
        	}
            e.printStackTrace();
            return false;
        }
       
    }

生成随机数工具类 :

public static String getRandomKey(int keyLength){
      int nt = 0;
      StringBuffer theKeyBuffer = new  StringBuffer();
      
      
      int ns = (int)(Math.random() * 1000000) << 6;
      while(ns > 0 && keyLength > 1){
          nt = ns % 36;
          ns = (int)(ns / 7);
          theKeyBuffer.append(arrayPool[nt]);
          exchangePoolData(nt);
          keyLength--;
      }
      
      
      ns = (int)System.currentTimeMillis() << 20;
      while(ns > 0 &&  keyLength > 1){
          nt = ns % 36;
          ns = (int)(ns / 7);
          theKeyBuffer.append(arrayPool[nt]);
          exchangePoolData(nt);
          keyLength--;
      }
      
      Calendar calendar = new GregorianCalendar();
      Date now = new Date();
      calendar.setTime(now);
      ns = calendar.get(Calendar.YEAR) * 365 + calendar.get(Calendar.MONTH) * 30 + calendar.get(Calendar.DATE);
      while(ns > 0 &&  keyLength > 1){
          nt = ns % 36;
          ns = (int)(ns / 7);
          theKeyBuffer.append(randomPool.substring(nt , nt + 1));
          keyLength--;
      }
      
      nt = ns % 36;
      theKeyBuffer.append(randomPool.substring(nt , nt + 1));
      if(keyLength > 2){
          theKeyBuffer.append(String.valueOf(keyLength - 1));
      }    
      
      if(theKeyBuffer.length() < 12 ){
          switch (theKeyBuffer.length()) {
              case 11 : theKeyBuffer.append('A');break;
              case 10 : theKeyBuffer.append("BB");break;
              case 9 : theKeyBuffer.append("CCC");break;
              case 8 : theKeyBuffer.append("DDDD");break;
          }
      }
      return theKeyBuffer.toString().toLowerCase();
  }

  /*
   * 初始化类标量
   */
  static StringBuffer randomPool = new StringBuffer("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
  static char[] arrayPool = new char[randomPool.length()];
  static {
      for(int i = 0 ; i < randomPool.length() ; i ++){
          arrayPool[i] = randomPool.charAt(i);
      }
  }
private static void exchangePoolData(int position){
      char tmp = arrayPool[0];
      for(int i = 1 ; i <= position ; i++){
      	arrayPool[i - 1] = arrayPool[i];
      }
      arrayPool[position] = tmp;
  }
共有 人打赏支持
粉丝 10
博文 50
码字总数 32092
作品 1
×
Alexdevlin
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: