您的位置:首页 > 理论基础 > 计算机网络

java 读取网络路径和本地路径的图片

2018-02-03 09:27 531 查看
一个读取网络路径和本地路径 图片的例子(亲测可用)

需求:

1.读取两种格式(网络路径和本地路径)的图片

2.用日志记录相关信息(引入commons-logging-1.1.jar包)

3.为了安全 ,对结果数据进行编码、解码,

问题:

首先为什么BASE64Encoder和BASE64Decoder在Eclipse中不能使用?

编码解码使用sun包下的BASE64Encoder和BASE64Decoder两个工具把任意序列的8位字节描述为一种不易被人直接识别的形式;但不能使用是因为他们是Sun公司专用的API,在Eclipse后来的版本中都不能直接使用,但是直接使用文本编辑器编写代码,然后使用javac编译,java去执行是没有问题的。

怎么设置才可以在Eclipse中使用BASE64Encoder和BASE64Decoder?

右击项目 --> Properties --> Java Build Path --> 点开JRE SystemLibrary --> 点击Access rules --> Edit --> Add --> Resolution选择Accessible--> Rule Pattern 填** --> OK

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TestReadImgWithUrlOrPath {
public static Log log=LogFactory.getLog(TestReadImgWithUrlOrPath.class);

public static void main(String s[]) throws IOException
{
String urlOrPath="C:\\Users\\jingtiancai\\Pictures\\kaola.jpg";

//String urlOrPath="http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg";
System.out.println(urlOrPath);
System.out.println(readImg(urlOrPath));

}
/*
* 读取远程和本地文件图片
*/
public static String readImg(String urlOrPath){
InputStream in = null;
try {
/////////////网络路径
if(urlOrPath.startsWith("http")){
URL url = new URL(urlOrPath);
in = url.openStream();
}else{ //////////////本地路径
File file = new File(urlOrPath);
if(!file.isFile() || !file.exists() || !file.canRead()){
log.info("图片不存在或文件错误");
return "error";
}
in = new FileInputStream(file);
}
byte[] b = getByte(in); //调用方法,得到输出流的字节数组
return base64ToStr(b);    //调用方法,为防止异常 ,得到编码后的结果

} catch (Exception e) {
log.error("读取图片发生异常:"+ e);
return "error";
}
}

public static byte[] getByte(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buf=new byte[1024]; //缓存数组
while(in.read(buf)!=-1){ //读取输入流中的数据放入缓存,如果读取完则循环条件为false;
out.write(buf); //将缓存数组中的数据写入out输出流,如果需要写到文件,使用输出流的其他方法
}
out.flush();
return out.toByteArray();	//将输出流的结果转换为字节数组的形式返回	(先执行finally再执行return	)
} finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}

/*
* 编码
* Base64被定义为:Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式
*/
public static String base64ToStr(byte[] bytes) throws IOException {
String content = "";
content = new BASE64Encoder().encode(bytes);
return content;
}
/*
* 解码
*/
public static byte[] strToBase64(String content) throws IOException {
if (null == content) {
return null;
}
return new BASE64Decoder().decodeBuffer(content.trim());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息