java io流根据url读取图片

//获取图片大小
public void readFileSize(String url,HttpServletRequest request){

//根路径

File file = new File(request.getRealPath("/")+url);
InputStream is = null;
FileImageOutputStream imageOutput=null;
//按图片名截取
String fileName=file.getName();
//按后缀截取
String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
try {
is = new BufferedInputStream(new FileInputStream(file));
int i=is.available()/1024;
if (i>30.4) {
// app.base.data_excel  存图片的路径
File imagePath = new File(Config.getKey("app.base.data_excel")+"picdatafor1/");
if (!imagePath.exists()) {
imagePath.mkdir();
}
byte[] getData = readInputStream(request.getRealPath("/")+url);
imageOutput = new FileImageOutputStream(new File(Config.getKey("app.base.data_excel")+"picdatafor1/"+fileName));
imageOutput.write(getData, 0, getData.length);
imageOutput.flush();
imageOutput.close();
}else if(i<=30.4 && "png".equals(prefix)){

FileWriter fw = new FileWriter(new File(Config.getKey("app.base.data_excel")+"pic.txt"),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileName);
bw.newLine();
bw.flush();
bw.close();
fw.close();

// 输出图片路径
byte[] getData = readInputStream(request.getRealPath("/")+url);
File imagePath = new File(Config.getKey("app.base.data_excel")+"picdatafor0/");
if (!imagePath.exists()) {
imagePath.mkdir();
}

imageOutput = new FileImageOutputStream(new File(Config.getKey("app.base.data_excel")+"picdatafor0/"+fileName),t);
imageOutput.write(getData, 0, getData.length);
imageOutput.flush();
imageOutput.close();

}else {
byte[] getData = readInputStream(request.getRealPath("/")+url);
File imagePath = new File(Config.getKey("app.base.data_excel")+"picdatafor2/");
if (!imagePath.exists()) {
imagePath.mkdir();
}

imageOutput = new FileImageOutputStream(new File(Config.getKey("app.base.data_excel")+"picdatafor2/"+fileName));
imageOutput.write(getData, 0, getData.length);
imageOutput.flush();
imageOutput.close();
}
} catch (FileNotFoundException e) {
// System.out.println("url不存在");
} catch (IOException e) {
e.printStackTrace();
}

finally{
if (is != null) {
try {
is.close(); // 关闭流
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

}

// 根据url读取文件
public static byte[] readInputStream(String url) throws IOException {
byte[] data = null;
FileImageInputStream input = new FileImageInputStream(new File(url));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024*1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
return data;
}

posted @ 2017-12-21 11:43  smallf  阅读(1834)  评论(0编辑  收藏  举报