문제

웹 사이트에서 이미지를 얻는 메소드가있는 Java 클래스가 있습니다.

private Image image;
private int height;
private int width;
private String imageUri;

public Image getImage() {
    if (image == null) {
        log.info("Fetching image: " + imageUri);
        try {
            URL iURL = new URL(imageUri);
            ImageIcon ii = new ImageIcon(iURL);
            image = ii.getImage();
            height = image.getHeight(null);
            width = image.getWidth(null);
        } catch (SecurityException e) {
            log.error("Unable to fetch image: " + imageUri,e);
        } catch (MalformedURLException e) {
            log.error("Unable to fetch image: " + imageUri,e);
        }
    }
    return image;
}

문제는 때때로 내가 가져 오려는 imageUri가 리디렉션되어 imageicon 생성자가 java.lang.securityException을 던지게한다는 것입니다.

누구든지 내가이 예외를 어떻게 잡을 수 있는지 제안 할 수 있습니까?

감사

도움이 되었습니까?

해결책 4

ImageIcon이 극도로 오래된 학교이고 새로운 스레드 (내가 원하지 않는)를 생성하기 때문에 내 솔루션은 다음과 같습니다.

public Image getImage() {
    if (image == null) {
        log.info("Fetching image: " + imageUri);
        try { 
            URL iURL = new URL(imageUri);
            InputStream is = new BufferedInputStream(iURL.openStream());
            image = ImageIO.read(is);
            height = image.getHeight();
            width = image.getWidth();
        } catch (MalformedURLException e) {
            log.error("Unable to fetch image: " + imageUri, e);
        } catch (IOException e) {
            log.error("Unable to fetch image: " + imageUri, e);
        }
    }
    return image;
}

리디렉션, 죽은 링크 등과 관련된 모든 문제는 이제 우아하게 처리됩니다.

다른 팁

예외는 생성자에 의해 던져지고 있으며, 이는 시도 블록에 싸여 있지 않습니다.

new ImageIcon(new URL(imageUri))

ImageIcon을 사용하여 이미지를로드하는 것은 Sooooo 1998입니다. imageio.read ().

예외가 실제로 getImage ()에서 던져지면 코드가 포착해야합니다. SecurityException은 예외입니다. 당신은 어딘가에 잘못되었습니다. 예를 들어, ImageIcon 생성자를 시도해보십시오. 도움이되지 않으면 시도하십시오

catch( Throwable th )

그래도 나쁜 습관입니다. 로깅 후 최소한 (또는 래퍼 예외)를 다시 줄이려고 노력하십시오.

이것은 오래된 스레드입니다. 그러나 나는 같은 문제에 도달 한 후이 게시물을 쳤을 때 대체 답변을 추가 할 생각을했습니다.

내 앱 (= javax)에 더 많은 종속성을 추가하고 싶지 않기 때문에 여기에 제안 된 해결책 비트 맵을 얻기 위해 사용했습니다 setimagebitmap 이 경우 SecurityException 잡히는 것

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top