美文网首页
java从线上读取图片转化为byte[]

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

作者: caopengflying | 来源:发表于2019-03-20 17:51 被阅读0次

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

源码如下

/**
     * 图片转为byte数组
     *
     * @param path
     * @return
     */
    public static byte[] image2byte(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;
    }

相关文章

网友评论

      本文标题:java从线上读取图片转化为byte[]

      本文链接:https://www.haomeiwen.com/subject/tcmtvqtx.html