2019년 10월 14일

자바에서 URL 이미지 가져오기 - Get Image From URL(JAVA)

자바에서 URL 이미지를 가져오는 것은 여러가지 방법이 있다. 직접 필요한 코드를 작성하는 방법도 있지만 Apache Commons IO 라이브러리를 사용하여 간단하게 간단하게 구현할 수 있다.

maven 을 사용하는 경우 pom.xml 파일에 다음의 의존성을 추가한다.
1
2
3
4
5
6
7
8
9
10
<dependency>
 <groupid>commons-io</groupid>
 <artifactid>commons-io</artifactid>
 <version>2.5</version>
</dependency>
<dependency>
    <groupid>org.apache.tika</groupid>
    <artifactid>tika-core</artifactid>
    <version>1.22</version>
</dependency>

이미지 파일은 임시파일을 생성하고 URL 연결을 통하여 읽어 드린 스트림을 저장하는 방식으로 구현하였다.
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
/** 예제 **/
 
package tests;
 
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;
 
import org.apache.commons.io.FileUtils;
import org.apache.tika.Tika;
 
public class DownloadImageFromUrlTest {
 
  
 public static void main(String args[]){
    
  try {
   // 다운로드를 위한 이미지 URL 정보
   URL url = new URL("https://...");
   File image = readFileFromUrl( url );
   String contentType = getContentType(image);
    
  } catch (Exception e) {
   e.printStackTrace();
  }
   
 }
  
 /**
  * get content type from file.
  * @param image
  * @return
  */
 public static String getContentType(File image) {
  String contentType = null;
  Tika tika = new Tika();
  try {
      contentType = tika.detect(image);
  } catch (IOException e) {
      contentType = null;
  }
     return contentType;
 }
  
 /**
  * read image file from url.
  * @param imageUrl
  * @return
  * @throws IOException
  */
 public static File readFileFromUrl(URL imageUrl) throws IOException {
     File temp = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
     temp.deleteOnExit();
     FileUtils.copyURLToFile(imageUrl, temp);
     return temp;
 }
}
위의 코드를 사용하는 경우 403 Forbidden 오류가 발생하는 경우가 많은데 이는 해당 웹 사이트에서 프로그램을 통한 접근을 차단하기 조치가 되어 있는 것으로 추측된다. 이경우는 URL 요청시 웹 브라우저에서 접근하는 것과 유사하게 요청 헤더에 USER_AGENT 값을 추가하여 해결할 수 있다.

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
/** 예제 **/
 
package tests;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
 
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tika.Tika;
 
public class DownloadImageFromUrlTest {
 
  
 public static void main(String args[]){
    
  try {
   // 다운로드를 위한 이미지 URL 정보
   URL url = new URL("https://...");
   File image = readFileFromUrl( url );
   String contentType = getContentType(image);
    
  } catch (Exception e) {
   e.printStackTrace();
  }
   
 }
  
 /**
  * get content type from file.
  * @param image
  * @return
  */
 public static String getContentType(File image) {
  String contentType = null;
  Tika tika = new Tika();
  try {
      contentType = tika.detect(image);
  } catch (IOException e) {
      contentType = null;
  }
     return contentType;
 }
 
 /**
  * read image file from url.
  * @param imageUrl
  * @return
  * @throws IOException
  */
 public static File readFileFromUrl(URL url) throws Exception {
  InputStream inputStream = null;
  try {
   String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
   URLConnection con = url.openConnection();
   con.setRequestProperty("User-Agent", USER_AGENT);
   inputStream = con.getInputStream();
   File temp = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
   FileUtils.copyToFile( inputStream, temp );
   return temp;
  }finally {
   IOUtils.closeQuietly(inputStream);
  }
 }
 
}
위의 코드를 적용하면 대부분의 사이트에서 이미지를 다운로드가 가능한 것으로 확인되었다. 다만 추가적인 보안 조치가 있는 경우는 동작하지 않을 수 있다.

댓글 없음:

댓글 쓰기