JAVA/Networking

[java/net] 인터넷 URL 이미지 주소로 파일 크기/형태 확인 URLConnection/openConnection

java나유 2022. 6. 27. 22:44

인터넷 URL 이미지 주소로 파일 크기/형태 확인 및 내 PC에 저장하는 법

 

public class net2 {

	public static void main(String[] args) throws Exception{
		
		Scanner sc = new Scanner(System.in);
		System.out.println("웹에서 가져올 이미지 주소를 입력하세요");
		String url =sc.next();
		
		URL u = new URL(url); //USL 메소드/사용자 입력값 선언
		
		URLConnection con = u.openConnection(); //URL 메소드 생성
		int imgsize = con.getContentLength(); // 이미지 크기 확인 
		System.out.println(imgsize); //이미지 크기 출력
		String imgtype=con.getContentType(); //이미지 TYPE 확인
		System.out.println(imgtype); // 이미지 TYPE 출력
	}
}

결과값:

이미지 크기는 247834 Byte

이미지 형태는 jpeg로 확인 되었습니다.

 

사용 메소드 

  • URL u = new URL(url); //url 선언
  • URLConnection //url연결
  • getContentLength //이미지 크기(길이)
  • getContentType//이미지 타입

 

 

 

제가 이미지로 사용한 url입니다.

https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2Fbv0e1m%2Fbtq6Qxyeeiw%2FAAAAAAAAAAAAAAAAAAAAAG6XZ0d1V-vw_q82DZ1J9kNFeuAAQk1_4RL-_zaCjeLh%2Fimg.jpg%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1753973999%26allow_ip%3D%26allow_referer%3D%26signature%3DFEZ%252BSVzXJdIcRxKRLR%252Fmo9cli%252BY%253D

 
728x90