liuxiaolong
2019-05-06 a7bed6b4cfecd61ec153818945f982c5bb796b98
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.cloud.common.utils;
 
 
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
/**
 * @author lp
 * @date 2018-08-05
 */
public class ReadUrlImg {
 
    public static InputStream getInputStream(String imgUrl) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(imgUrl);
            if (url != null) {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == HttpStatus.OK.value()) {
                    inputStream = httpURLConnection.getInputStream();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
 
    }
 
    public static void saveImage() {
        InputStream inputStream = getInputStream("");
        FileOutputStream fileOutputStream = null;
        byte[] data = new byte[1024];
        int len = 0;
        try {
            fileOutputStream = new FileOutputStream("D:\\2.jpg");
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
 
    }
 
 
    /**
     * 根据图片路径获取Byte数组
     * @param imgUrl
     * @return
     * @throws IOException
     */
    public static byte[] getImgByte(String imgUrl) throws IOException {
        InputStream inputStream = getInputStream(imgUrl);
        if (inputStream != null) {
            return IOUtils.toByteArray(inputStream);
        }
        return null;
    }
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        saveImage();
    }
 
}