BASE64图片处理的相关方法

阅读更多
图片压缩方法:
  public static byte[] compressImg(File imgFile,int width,int height){
   if(imgFile.exists()){
    byte[] buffer=null;
    try{
    Image bi=ImageIO.read(imgFile);
    //BufferedImage tmpimg=ImageIO.read(imgFile);
    //bi.getWidth(null);
    ImageIcon icon=new ImageIcon(bi);
    if((icon.getIconHeight()*icon.getIconWidth())>width*height){
     int w=width;
     int h=height;
     int w1=icon.getIconWidth();
     int h1=icon.getIconHeight();
     //等比例缩放
     if(w1/w>h1/h){
      height=h1*w/w1;
     }else{
      width=w1*h/h1;
     }
     bi= bi.getScaledInstance(width,height,Image.SCALE_DEFAULT);
     BufferedImage mBufferedImage = new BufferedImage(width,height ,BufferedImage.TYPE_INT_RGB);
     Graphics2D g2 = mBufferedImage.createGraphics();
        g2.drawImage(bi, 0, 0,width, height, Color.white,null);
        g2.dispose();
        ImageIO.write(mBufferedImage,"jpg",imgFile);
    }
       //File outFile = null;
       //BufferedImage tmpimg=(BufferedImage) bi;
//       ImageIO.write(tmpimg, "jpg", imgFile);
     
     
   
       buffer=new byte[(int) imgFile.length()];
       InputStream is = new FileInputStream(imgFile);
      
       is.read(buffer);
    }catch(Exception e){
     e.printStackTrace();
    }
       return buffer;
   }else{
    return null;
   }
  }
BASE64加密:
BASE64Encoder base64=new BASE64Encoder();
InputStream is=图片文件流,可以通过数据库读取;
   if(is!=null){
    byte imgdata[] = Utils.compressImg(is, 120, 150);
//    byte imgdata1[]=get.switchInputStream(is);
    String img=base64.encode(imgdata);
    result.put("IMG", img);
   }else{
    result.put("IMG", null);
   }
页面处理:
jsp1:
" width="120" height="150" border="0" style="border:1px solid #000000">
img.jsp代码:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.io.*,sun.misc.BASE64Decoder,java.awt.image.*,cn.sz.iaspec.ddd.web.BaseValueObject,java.util.*,com.sun.image.codec.jpeg.JPEGCodec,com.sun.image.codec.jpeg.JPEGImageEncoder"%>
<%
String strdata=(String)request.getParameter("imgdata");
strdata=strdata.replaceAll(" ","+");//关键的地方,用get的方法传参会使"+"变成" ",所以需要进行替换
BASE64Decoder base=new BASE64Decoder();
byte img[]=base.decodeBuffer(strdata);
InputStream in = new ByteArrayInputStream(img);
BufferedImage image = javax.imageio.ImageIO.read(in);
out.clear();
out = pageContext.pushBody();
ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
sos.close();
%>

你可能感兴趣的:(java,jsp,sun,web)