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:
<img src="img.jsp?imgdata=<%=bo.getStringField("IMG")%>" 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();
%>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值