使用ByteArrayOutputStream输出二进制流文件
话不多说直接上代码
标题实现类
public byte[] getPicDataById(String id,String path) throws IOException{
BufferedImage image = ImageIO.read(new File(path));//获取图片
Graphics g = image.getGraphics();
g.setColor(Color.GREEN);//画笔颜色
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10.0f));//画笔粗细
postion.forEach(p->{
g.drawRect(p.getQiPosition1(), p.getQiPosition2(), p.getQiPosition3()-p.getQiPosition1(), p.getQiPosition4()-p.getQiPosition1());//矩形框(原点x坐标,原点y坐标,矩形的长,矩形的宽)//这个地方填写你自己的坐标
});
g.dispose();
ByteArrayOutputStream outpu = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", outpu);//获取内存中的图片
byte[] date = outpu.toByteArray();//存放到byte数组中
return date;
}
controller
public void getPicDataById(@RequestParam(name="id",required=true) String id,HttpServletRequest request,HttpServletResponse response) throws IOException {
byte[] data = bizQualityfileService.getPicDataById(id);
data = compressImage(data,500);
response.setContentType("image/jpeg");
response.getOutputStream().write(data);
response.getOutputStream().flush();
response.getOutputStream().close();
}
免费附赠压缩图片方法
public static byte[] compressImage(byte[] imageByte, int ppi) {
byte[] smallImage = null;
int width = 0, height = 0;
if (imageByte == null)
return null;
ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
try {
Image image = ImageIO.read(byteInput);
int w = image.getWidth(null);
int h = image.getHeight(null);
// adjust weight and height to avoid image distortion
double scale = 0;
scale = Math.min((float) ppi / w, (float) ppi / h);
width = (int) (w * scale);
width -= width % 4;
height = (int) (h * scale);
if (scale >= (double) 1)
return imageByte;
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(buffImg, "png", out);
smallImage = out.toByteArray();
return smallImage;
} catch (IOException e) {
log.error(e.getMessage());
return null;
}