<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近做网站时,经常会对图片进行操作,用到的基本操作如下:</span>
1.读取图片到 二进制数组中
ByteArrayOutputStream out = null ;
BufferedInputStream in = null;
File file = new File(relativePath);
in = new BufferedInputStream(new FileInputStream(file));
out = new ByteArrayOutputStream((int)file.length());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer, 0, buffer.length)) != - 1) {
out.write(buffer, 0, len);
}
in.close();
byte[] blob= out.toByteArray();
ByteArrayOutputStream 的flush和close都做的空操作,所以没必要写上去。
2.二进制数据到写入图片
public static String saveFile(String path, byte[] blob) {
if(blob == null) {
return null;
}
File file = new File(TheApp.getRootPath(path));
if (file.exists()) {
return null;
}
// 创建父目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
if (!file.getParentFile().exists()) {
logger.error("创建文件目录失败!");
return null;
}
}
// 写数据
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(blob);
out.flush();
}
catch (Exception e) {
logger.error("写文件失败:" + path);
file.delete();
return null;
}
finally {
close(out);
}
return path.toString();
}
3.图片传输
图片传输 用的是base64数据格式
用到的org.apache.xerces.impl.dv.util里面的Base64.encode()和Base64.decode();
4.图片压缩
对于比较大的图片 保存之前需要等比例 缩小下
ByteArrayInputStream in= new ByteArrayInputStream(blob);
BufferedImage bufferImage = ImageIO.read(in); //将in作为输入流,读取图片存入image中,而这里in可以为ByteArrayInputStream();
Image srcImg =(Image) bufferImage ;//取源图
int width = 100; //假设要缩小到100点像素
int height = srcImg.getHeight(null)*100/srcImg.getWidth(null);//按比例,将高度缩减
Image smallImg =srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);//缩小
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = bi.getGraphics();
g.drawImage(smallImg, 0, 0, null);
ByteArrayOutputStream newByte=new ByteArrayOutputStream();
ImageIO.write(bi,"jpg",newByte);
byte[] out=newByte.toByteArray();
5.图片网页显示
传输时,传输的是一个相对路径
网页中用img.src 接收即可