[Java] BufferedImage类的相关处理

公司需要做一个九格切图功能, 方便发布至朋友圈. 本来用Python三十行搞定. 但是被测试部diss了说我不会用Java写, 当时一时气不过用原生Java又写了一个, 整整一百五十行… 我的青春啊

中间踩了BufferedImage的很多坑, 在此总结一下BufferedImage的一些用法

通过URL读取BufferedImage
	// 需要对IOException进行处理, 一共两处, 在URL连接处和文件读取处
	URL url = new URL("http://yihezo.cn/static/media/logo.9d4a5ade.png");
	URLConnection connection = url.openConnection(); //打开连接
    connection.setDoOutput(true);
    connection.setReadTimeout(3000);// 设置超时时间(非必须)
    BufferedImage img = ImageIO.read(connection.getInputStream());
通过本地文件路径读取BufferedImage
	File file = new File("C:/a.png");
	BufferedImage img = ImageIO.read(new FileInputStream(file));
BufferedImage转Base64
	// img为上面获取到的图片, 类型同为BufferedImage
	ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
    ImageIO.write(img, "png", baos);//写入流中
    byte[] bytes = baos.toByteArray();//转换成字节
    BASE64Encoder encoder = new BASE64Encoder();
    String base64Code = encoder.encodeBuffer(bytes).trim();
Base64转BufferedImage
	String base64Code = ""; // base64编码过长, 此处不放示例
	BASE64Decoder decoder = new BASE64Decoder();
    byte[] bytes1 = decoder.decodeBuffer(base64Code);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
    BufferedImage img = ImageIO.read(bais);
裁剪BufferedImage
	/* 
	* img为上面获取到的图片, 类型同为BufferedImage 
	* getSubimage(x轴坐标, y轴坐标, x轴坐标向右距离长度, y轴坐标向下距离长度) 
	* 左上角坐标为0,0 
	*/
	BufferedImage newImg= img.getSubimage(0, 0, 20, 30);
保存BufferedImage
	File f = new File("E:/Test.png");
    ImageIO.write(resImg, "png", f);
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值