通过url下载图片
需求:通過url從服務器上獲取圖片,將圖片轉換成base64的字符串用來做業務。
代碼:
package com.su.mybatis.oracle.controller;import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;import org.apache.commons.codec.binary.Base64;public class Test {public static void main(String[] args) {String imageBase64 = "";String path = "xxxxxxx";//圖片urltry {imageBase64 = getImageByPath(path);} catch (IOException e) {e.printStackTrace();}System.out.println(imageBase64);//TODO 做自己的業務}public static String getImageByPath(String path) throws IOException { URL url = null;HttpURLConnection httpUrl = null; InputStream in = null; byte[] data = null; try {url = new URL(path);httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); in = httpUrl.getInputStream(); data = new byte[in.available()]; in.read(data); } catch (IOException e) { e.printStackTrace();} finally {if(in != null)in.close(); } return data == null ? "" : Base64.encodeBase64String(data); } }?
?
如果有寫的不對的地方,請大家多多批評指正,非常感謝!
總結
- 上一篇: 尝试用ubuntu 22.04 LTS系
- 下一篇: 双阶乘C语言,c阶乘公式(排列组合与阶乘