Java从线上读取图片转化为byte[]

123 阅读1分钟

源码如下:

/**
 * 线上图片转为byte数组
 *
 * @param path
 * @return
 */
public static byte[] onlineImage2byte(String path) throws IOException {
    byte[] data = null;
    URL url = null;
    InputStream input = null;
    try{
        url = new URL(path);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        httpUrl.connect();
        httpUrl.getInputStream();
        input = httpUrl.getInputStream();
    }catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int numBytesRead = 0;
    while ((numBytesRead = input.read(buf)) != -1) {
        output.write(buf, 0, numBytesRead);
    }
    data = output.toByteArray();
    output.close();
    input.close();
    return data;
}