欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将网络图片转化成base64格式

程序员文章站 2022-03-30 21:59:23
...

只需要传url即可

private static String strNetImageToBase64;
	private String NetImageToBase64(String netImagePath) {
		final ByteArrayOutputStream data = new ByteArrayOutputStream();
		String s = null;
		try {
			// 创建URL
			URL url = new URL(netImagePath);
			final byte[] by = new byte[1024];
			// 创建链接
			final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);

			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						InputStream is = conn.getInputStream();
						// 将内容读取内存中
						int len = -1;
						while ((len = is.read(by)) != -1) {
							data.write(by, 0, len);
						}
						// 对字节数组Base64编码
						BASE64Encoder encoder = new BASE64Encoder();
						strNetImageToBase64 = encoder.encode(data.toByteArray());
						// 关闭流
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return strNetImageToBase64;
	}