static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
public static String getImageBinary(String Imgpath){
File f = new File(Imgpath);
BufferedImage bi;
try {
bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void base64StringToImage(String savePath,String base64String){
try {
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 =ImageIO.read(bais);
File w2 = new File(savePath);//可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
}
上传服务器:
ImageBinary.base64StringToImage("/home/bigbusdata-files/"+filesname, file);
注意保存路径最后有 /
tomcat 设置外置保存路径
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<Context docBase="/home/bigbusdata-files" path="/busFiles" reloadable="true" /> </Host>
访问tomcat的/busFiles,相当于访问服务器的 /home/bigbusdata-files 目录