修改图片画矩形输出二进制流

使用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;
		 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值